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,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/Core.Wpf/WpfClassificationExtensions.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.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class WpfClassificationExtensions { public static Run ToRun(this ClassifiedText part, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var run = new Run(part.Text); var classificationType = typeMap.GetClassificationType(part.ClassificationType); var format = formatMap.GetTextProperties(classificationType); run.SetTextProperties(format); return run; } public static IList<Inline> ToInlines( this IEnumerable<ClassifiedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, Action<Run, ClassifiedText, int> runCallback = null) { var inlines = new List<Inline>(); var position = 0; foreach (var part in parts) { var run = part.ToRun(formatMap, typeMap); runCallback?.Invoke(run, part, position); inlines.Add(run); position += part.Text.Length; } return inlines; } public static IList<Inline> ToInlines( this IEnumerable<TaggedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var classifiedTexts = parts.Select(p => new ClassifiedText( p.Tag.ToClassificationTypeName(), p.ToVisibleDisplayString(includeLeftToRightMarker: true))); return classifiedTexts.ToInlines(formatMap, typeMap); } public static TextBlock ToTextBlock( this IEnumerable<TaggedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var inlines = parts.ToInlines(formatMap, typeMap); return inlines.ToTextBlock(formatMap); } [Obsolete("Use 'public static TextBlock ToTextBlock(this IEnumerable <Inline> inlines, IClassificationFormatMap formatMap, bool wrap = true)' instead")] public static TextBlock ToTextBlock( this IEnumerable<Inline> inlines, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, string classificationFormatMap = null, bool wrap = true) => inlines.ToTextBlock(formatMap, wrap); public static TextBlock ToTextBlock( this IEnumerable<Inline> inlines, IClassificationFormatMap formatMap, bool wrap = true) { var textBlock = new TextBlock { TextWrapping = wrap ? TextWrapping.Wrap : TextWrapping.NoWrap, TextTrimming = wrap ? TextTrimming.None : TextTrimming.CharacterEllipsis }; textBlock.SetDefaultTextProperties(formatMap); textBlock.Inlines.AddRange(inlines); return textBlock; } public static TextBlock ToTextBlock(this TaggedText part, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) => SpecializedCollections.SingletonEnumerable(part).ToTextBlock(formatMap, typeMap); } }
// 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.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class WpfClassificationExtensions { public static Run ToRun(this ClassifiedText part, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var run = new Run(part.Text); var classificationType = typeMap.GetClassificationType(part.ClassificationType); var format = formatMap.GetTextProperties(classificationType); run.SetTextProperties(format); return run; } public static IList<Inline> ToInlines( this IEnumerable<ClassifiedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, Action<Run, ClassifiedText, int> runCallback = null) { var inlines = new List<Inline>(); var position = 0; foreach (var part in parts) { var run = part.ToRun(formatMap, typeMap); runCallback?.Invoke(run, part, position); inlines.Add(run); position += part.Text.Length; } return inlines; } public static IList<Inline> ToInlines( this IEnumerable<TaggedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var classifiedTexts = parts.Select(p => new ClassifiedText( p.Tag.ToClassificationTypeName(), p.ToVisibleDisplayString(includeLeftToRightMarker: true))); return classifiedTexts.ToInlines(formatMap, typeMap); } public static TextBlock ToTextBlock( this IEnumerable<TaggedText> parts, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) { var inlines = parts.ToInlines(formatMap, typeMap); return inlines.ToTextBlock(formatMap); } [Obsolete("Use 'public static TextBlock ToTextBlock(this IEnumerable <Inline> inlines, IClassificationFormatMap formatMap, bool wrap = true)' instead")] public static TextBlock ToTextBlock( this IEnumerable<Inline> inlines, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, string classificationFormatMap = null, bool wrap = true) => inlines.ToTextBlock(formatMap, wrap); public static TextBlock ToTextBlock( this IEnumerable<Inline> inlines, IClassificationFormatMap formatMap, bool wrap = true) { var textBlock = new TextBlock { TextWrapping = wrap ? TextWrapping.Wrap : TextWrapping.NoWrap, TextTrimming = wrap ? TextTrimming.None : TextTrimming.CharacterEllipsis }; textBlock.SetDefaultTextProperties(formatMap); textBlock.Inlines.AddRange(inlines); return textBlock; } public static TextBlock ToTextBlock(this TaggedText part, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap) => SpecializedCollections.SingletonEnumerable(part).ToTextBlock(formatMap, typeMap); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private async Task<(Document document, SolutionPreviewResult previews)> GetMainDocumentAndPreviewsAsync(TestParameters parameters, TestWorkspace workspace) { var document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var previews = await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); return (document, previews); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); var (document, previews) = await GetMainDocumentAndPreviewsAsync(parameters, workspace); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.Ordinal); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings { public partial class PreviewTests : AbstractCSharpCodeActionTest { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts( typeof(MockDiagnosticUpdateSourceRegistrationService), typeof(MockPreviewPaneService)); private const string AddedDocumentName = "AddedDocument"; private const string AddedDocumentText = "class C1 {}"; private static string s_removedMetadataReferenceDisplayName = ""; private const string AddedProjectName = "AddedProject"; private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId(); private const string ChangedDocumentText = "class C {}"; protected override TestComposition GetComposition() => s_composition; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new MyCodeRefactoringProvider(); private class MyCodeRefactoringProvider : CodeRefactoringProvider { public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var codeAction = new MyCodeAction(context.Document); context.RegisterRefactoring(codeAction, context.Span); return Task.CompletedTask; } private class MyCodeAction : CodeAction { private readonly Document _oldDocument; public MyCodeAction(Document document) => _oldDocument = document; public override string Title { get { return "Title"; } } protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var solution = _oldDocument.Project.Solution; // Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText); // Remove a reference - This will result in a string preview. var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1]; s_removedMetadataReferenceDisplayName = removedReference.Display; solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference); // Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp)); // Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken)); return Task.FromResult(solution); } } } private async Task<(Document document, SolutionPreviewResult previews)> GetMainDocumentAndPreviewsAsync(TestParameters parameters, TestWorkspace workspace) { var document = GetDocument(workspace); var provider = CreateCodeRefactoringProvider(workspace, parameters); var span = document.GetSyntaxRootAsync().Result.Span; var refactorings = new List<CodeAction>(); var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None); provider.ComputeRefactoringsAsync(context).Wait(); var action = refactorings.Single(); var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var previews = await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None); return (document, previews); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")] public async Task TestPickTheRightPreview_NoPreference() { var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions("class D {}", parameters); var (document, previews) = await GetMainDocumentAndPreviewsAsync(parameters, workspace); // The changed document comes first. var previewObjects = await previews.GetPreviewsAsync(); var preview = previewObjects[0]; Assert.NotNull(preview); Assert.True(preview is DifferenceViewerPreview); var diffView = preview as DifferenceViewerPreview; var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); Assert.Equal(ChangedDocumentText, text); diffView.Dispose(); // Then comes the removed metadata reference. preview = previewObjects[1]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal); // And finally the added project. preview = previewObjects[2]; Assert.NotNull(preview); Assert.True(preview is string); text = preview as string; Assert.Contains(AddedProjectName, text, StringComparison.Ordinal); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractFormattingRule GetMultiLineFormattingRule(); #if CODE_STYLE protected abstract ISyntaxFormattingService GetSyntaxFormattingService(); #endif protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation); protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement); protected abstract Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken); protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defer to our callback to actually make the edits for each diagnostic. In turn, it // will return 'true' if it made a multi-line conditional expression. In that case, // we'll need to explicitly format this node so we can get our special multi-line // formatting in VB and C#. var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); foreach (var diagnostic in diagnostics) { await FixOneAsync( document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false); } var changedRoot = nestedEditor.GetChangedRoot(); // Get the language specific rule for formatting this construct and call into the // formatted to explicitly format things. Note: all we will format is the new // conditional expression as that's the only node that has the appropriate // annotation on it. var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() }; var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken); #if CODE_STYLE var formattedRoot = FormatterHelper.Format(changedRoot, GetSyntaxFormattingService(), SpecializedFormattingAnnotation, options, rules, cancellationToken); #else var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, rules, cancellationToken); #endif changedRoot = formattedRoot; editor.ReplaceNode(root, changedRoot); } /// <summary> /// Helper to create a conditional expression out of two original IOperation values /// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate /// annotations and casts to ensure that the conditional expression preserves semantics, but /// is also properly simplified and formatted. /// </summary> protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync( Document document, IConditionalOperation ifOperation, IOperation trueStatement, IOperation falseStatement, IOperation trueValue, IOperation falseValue, bool isRef, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var condition = ifOperation.Condition.Syntax; if (!isRef) { // If we are going to generate "expr ? true : false" then just generate "expr" // instead. if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false)) { return (TExpressionSyntax)condition.WithoutTrivia(); } // If we are going to generate "expr ? false : true" then just generate "!expr" // instead. if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true)) { return (TExpressionSyntax)generator.Negate(generatorInternal, condition, semanticModel, cancellationToken).WithoutTrivia(); } } var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression( condition.WithoutTrivia(), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue))); conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation); var makeMultiLine = await MakeMultiLineAsync( document, condition, trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false); if (makeMultiLine) { conditionalExpression = conditionalExpression.WithAdditionalAnnotations( SpecializedFormattingAnnotation); } return MakeRef(generatorInternal, isRef, conditionalExpression); } private static bool IsBooleanLiteral(IOperation trueValue, bool val) { if (trueValue is ILiteralOperation) { var constant = trueValue.ConstantValue; return constant.HasValue && constant.Value is bool b && b == val; } return false; } private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode) => isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode; /// <summary> /// Checks if we should wrap the conditional expression over multiple lines. /// </summary> private static async Task<bool> MakeMultiLineAsync( Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax, CancellationToken cancellationToken) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) || !sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) || !sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken())) { return true; } #if CODE_STYLE var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength); #endif if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength) { return true; } return false; } private TExpressionSyntax CastValueIfNecessary( SyntaxGenerator generator, IOperation statement, IOperation value) { if (statement is IThrowOperation throwOperation) return ConvertToExpression(throwOperation); var sourceSyntax = value.Syntax.WithoutTrivia(); // If there was an implicit conversion generated by the compiler, then convert that to an // explicit conversion inside the condition. This is needed as there is no type // inference in conditional expressions, so we need to ensure that the same conversions // that were occurring previously still occur after conversion. Note: the simplifier // will remove any of these casts that are unnecessary. if (value is IConversionOperation conversion && conversion.IsImplicit && conversion.Type != null && conversion.Type.TypeKind != TypeKind.Error) { // Note we only add the cast if the source had no type (like the null literal), or a // non-error type itself. We don't want to insert lots of casts in error code. if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error) { return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax); } } return (TExpressionSyntax)sourceSyntax; } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractFormattingRule GetMultiLineFormattingRule(); #if CODE_STYLE protected abstract ISyntaxFormattingService GetSyntaxFormattingService(); #endif protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation); protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement); protected abstract Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken); protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defer to our callback to actually make the edits for each diagnostic. In turn, it // will return 'true' if it made a multi-line conditional expression. In that case, // we'll need to explicitly format this node so we can get our special multi-line // formatting in VB and C#. var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); foreach (var diagnostic in diagnostics) { await FixOneAsync( document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false); } var changedRoot = nestedEditor.GetChangedRoot(); // Get the language specific rule for formatting this construct and call into the // formatted to explicitly format things. Note: all we will format is the new // conditional expression as that's the only node that has the appropriate // annotation on it. var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() }; var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken); #if CODE_STYLE var formattedRoot = FormatterHelper.Format(changedRoot, GetSyntaxFormattingService(), SpecializedFormattingAnnotation, options, rules, cancellationToken); #else var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, rules, cancellationToken); #endif changedRoot = formattedRoot; editor.ReplaceNode(root, changedRoot); } /// <summary> /// Helper to create a conditional expression out of two original IOperation values /// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate /// annotations and casts to ensure that the conditional expression preserves semantics, but /// is also properly simplified and formatted. /// </summary> protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync( Document document, IConditionalOperation ifOperation, IOperation trueStatement, IOperation falseStatement, IOperation trueValue, IOperation falseValue, bool isRef, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var condition = ifOperation.Condition.Syntax; if (!isRef) { // If we are going to generate "expr ? true : false" then just generate "expr" // instead. if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false)) { return (TExpressionSyntax)condition.WithoutTrivia(); } // If we are going to generate "expr ? false : true" then just generate "!expr" // instead. if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true)) { return (TExpressionSyntax)generator.Negate(generatorInternal, condition, semanticModel, cancellationToken).WithoutTrivia(); } } var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression( condition.WithoutTrivia(), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue))); conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation); var makeMultiLine = await MakeMultiLineAsync( document, condition, trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false); if (makeMultiLine) { conditionalExpression = conditionalExpression.WithAdditionalAnnotations( SpecializedFormattingAnnotation); } return MakeRef(generatorInternal, isRef, conditionalExpression); } private static bool IsBooleanLiteral(IOperation trueValue, bool val) { if (trueValue is ILiteralOperation) { var constant = trueValue.ConstantValue; return constant.HasValue && constant.Value is bool b && b == val; } return false; } private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode) => isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode; /// <summary> /// Checks if we should wrap the conditional expression over multiple lines. /// </summary> private static async Task<bool> MakeMultiLineAsync( Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax, CancellationToken cancellationToken) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) || !sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) || !sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken())) { return true; } #if CODE_STYLE var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength); #endif if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength) { return true; } return false; } private TExpressionSyntax CastValueIfNecessary( SyntaxGenerator generator, IOperation statement, IOperation value) { if (statement is IThrowOperation throwOperation) return ConvertToExpression(throwOperation); var sourceSyntax = value.Syntax.WithoutTrivia(); // If there was an implicit conversion generated by the compiler, then convert that to an // explicit conversion inside the condition. This is needed as there is no type // inference in conditional expressions, so we need to ensure that the same conversions // that were occurring previously still occur after conversion. Note: the simplifier // will remove any of these casts that are unnecessary. if (value is IConversionOperation conversion && conversion.IsImplicit && conversion.Type != null && conversion.Type.TypeKind != TypeKind.Error) { // Note we only add the cast if the source had no type (like the null literal), or a // non-error type itself. We don't want to insert lots of casts in error code. if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error) { return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax); } } return (TExpressionSyntax)sourceSyntax; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_INoPiaObjectCreationOperation.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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_INoPiaObjectCreationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ y }') Initializers(1): IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'ITest33') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { P = y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ P = y }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'P') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33()/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { y }; }/*</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 (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: null IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33 { y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33 { y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { P = y }; }/*</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 (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { P = y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... { P = y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... { P = y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33()') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') Right: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_04() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(object x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, object y1, object y2) { x = new ITest33 { y1 ?? y2 }; }/*</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 (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 ... y1 ?? y2 }') Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [3] .locals {R3} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation (virtual void ITest33.Add(System.Object x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y1 ?? y2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y1 ?? y2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1 ?? y2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... y1 ?? y2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... y1 ?? y2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: 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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_INoPiaObjectCreationOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ y }') Initializers(1): IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'ITest33') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33 { P = y }/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: ITest33) (Syntax: '{ P = y }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: ITest33, IsImplicit) (Syntax: 'P') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void NoPiaObjectCreation_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { public void M1(ITest33 x, int y) { x = /*<bind>*/new ITest33()/*</bind>*/; } } "; string expectedOperationTree = @" INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ObjectCreationExpressionSyntax>(consumer, expectedOperationTree, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_01() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(int x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { y }; }/*</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 (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { y }') Initializer: null IInvocationOperation (virtual void ITest33.Add(System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33 { y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33 { y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_02() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { int P {get; set;} } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33 { P = y }; }/*</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 (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 { P = y }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 { P = y }') Initializer: null ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'P = y') Left: IPropertyReferenceOperation: System.Int32 ITest33.P { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... { P = y };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... { P = y }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 { P = y }') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_03() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, int y) { x = new ITest33(); }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITest33();') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITest33()') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') Right: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33()') Initializer: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void NoPiaObjectCreationFlow_04() { string pia = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [assembly: PrimaryInteropAssemblyAttribute(1,1)] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [CoClass(typeof(ClassITest33))] public interface ITest33 : System.Collections.IEnumerable { void Add(object x); } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest33 { } "; var piaCompilation = CreateCompilation(pia, options: TestOptions.ReleaseDll); CompileAndVerify(piaCompilation); string consumer = @" class UsePia { /*<bind>*/public void M1(ITest33 x, object y1, object y2) { x = new ITest33 { y1 ?? y2 }; }/*</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 (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ITest33) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Value: INoPiaObjectCreationOperation (OperationKind.None, Type: ITest33) (Syntax: 'new ITest33 ... y1 ?? y2 }') Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [3] .locals {R3} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IInvocationOperation (virtual void ITest33.Add(System.Object x)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'y1 ?? y2') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y1 ?? y2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y1 ?? y2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = new ITe ... y1 ?? y2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ITest33) (Syntax: 'x = new ITe ... y1 ?? y2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ITest33, IsImplicit) (Syntax: 'new ITest33 ... y1 ?? y2 }') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<MethodDeclarationSyntax>(consumer, expectedFlowGraph, expectedDiagnostics, references: new[] { piaCompilation.EmitToImageReference(embedInteropTypes: true) }); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.ConvertValueToReturnsRewriter.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.ReplacePropertyWithMethods { internal partial class CSharpReplacePropertyWithMethodsService { private class ConvertValueToReturnsRewriter : CSharpSyntaxRewriter { public static readonly CSharpSyntaxRewriter Instance = new ConvertValueToReturnsRewriter(); private ConvertValueToReturnsRewriter() { } private static XmlNameSyntax ConvertToReturns(XmlNameSyntax name) => name.ReplaceToken(name.LocalName, SyntaxFactory.Identifier("returns")); public override SyntaxNode VisitXmlElementStartTag(XmlElementStartTagSyntax node) => IsValueName(node.Name) ? node.ReplaceNode(node.Name, ConvertToReturns(node.Name)) : base.VisitXmlElementStartTag(node); public override SyntaxNode VisitXmlElementEndTag(XmlElementEndTagSyntax node) => IsValueName(node.Name) ? node.ReplaceNode(node.Name, ConvertToReturns(node.Name)) : base.VisitXmlElementEndTag(node); } } }
// 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.ReplacePropertyWithMethods { internal partial class CSharpReplacePropertyWithMethodsService { private class ConvertValueToReturnsRewriter : CSharpSyntaxRewriter { public static readonly CSharpSyntaxRewriter Instance = new ConvertValueToReturnsRewriter(); private ConvertValueToReturnsRewriter() { } private static XmlNameSyntax ConvertToReturns(XmlNameSyntax name) => name.ReplaceToken(name.LocalName, SyntaxFactory.Identifier("returns")); public override SyntaxNode VisitXmlElementStartTag(XmlElementStartTagSyntax node) => IsValueName(node.Name) ? node.ReplaceNode(node.Name, ConvertToReturns(node.Name)) : base.VisitXmlElementStartTag(node); public override SyntaxNode VisitXmlElementEndTag(XmlElementEndTagSyntax node) => IsValueName(node.Name) ? node.ReplaceNode(node.Name, ConvertToReturns(node.Name)) : base.VisitXmlElementEndTag(node); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.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.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSymbolDisplayService : ISymbolDisplayService { protected readonly IAnonymousTypeDisplayService AnonymousTypeDisplayService; protected AbstractSymbolDisplayService(IAnonymousTypeDisplayService anonymousTypeDisplayService) => AnonymousTypeDisplayService = anonymousTypeDisplayService; protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken); public Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, SymbolDescriptionGroups groups, CancellationToken cancellationToken) => ToDescriptionStringAsync(workspace, semanticModel, position, ImmutableArray.Create<ISymbol>(symbol), groups, cancellationToken); public async Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { var parts = await ToDescriptionPartsAsync(workspace, semanticModel, position, symbols, groups, cancellationToken).ConfigureAwait(false); return parts.ToDisplayString(); } public async Task<ImmutableArray<SymbolDisplayPart>> ToDescriptionPartsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) { return ImmutableArray.Create<SymbolDisplayPart>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> ToDescriptionGroupsAsync( Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) { return SpecializedCollections.EmptyDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionSectionsAsync(symbols).ConfigureAwait(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.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSymbolDisplayService : ISymbolDisplayService { protected readonly IAnonymousTypeDisplayService AnonymousTypeDisplayService; protected AbstractSymbolDisplayService(IAnonymousTypeDisplayService anonymousTypeDisplayService) => AnonymousTypeDisplayService = anonymousTypeDisplayService; protected abstract AbstractSymbolDescriptionBuilder CreateDescriptionBuilder(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken); public Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ISymbol symbol, SymbolDescriptionGroups groups, CancellationToken cancellationToken) => ToDescriptionStringAsync(workspace, semanticModel, position, ImmutableArray.Create<ISymbol>(symbol), groups, cancellationToken); public async Task<string> ToDescriptionStringAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { var parts = await ToDescriptionPartsAsync(workspace, semanticModel, position, symbols, groups, cancellationToken).ConfigureAwait(false); return parts.ToDisplayString(); } public async Task<ImmutableArray<SymbolDisplayPart>> ToDescriptionPartsAsync(Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, SymbolDescriptionGroups groups, CancellationToken cancellationToken) { if (symbols.Length == 0) { return ImmutableArray.Create<SymbolDisplayPart>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionAsync(symbols, groups).ConfigureAwait(false); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> ToDescriptionGroupsAsync( Workspace workspace, SemanticModel semanticModel, int position, ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { if (symbols.Length == 0) { return SpecializedCollections.EmptyDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(); } var builder = CreateDescriptionBuilder(workspace, semanticModel, position, cancellationToken); return await builder.BuildDescriptionSectionsAsync(symbols).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/LanguageServer/Protocol/Handler/RequestShutdownEventArgs.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.LanguageServer.Handler { internal class RequestShutdownEventArgs : EventArgs { public string Message { get; } public RequestShutdownEventArgs(string message) { this.Message = message; } } }
// 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.LanguageServer.Handler { internal class RequestShutdownEventArgs : EventArgs { public string Message { get; } public RequestShutdownEventArgs(string message) { this.Message = message; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/ExtractMethod/OperationStatus_Statics.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.ExtractMethod { internal partial class OperationStatus { public static readonly OperationStatus Succeeded = new(OperationStatusFlag.Succeeded, reason: null); public static readonly OperationStatus FailedWithUnknownReason = new(OperationStatusFlag.None, reason: FeaturesResources.Unknown_error_occurred); public static readonly OperationStatus OverlapsHiddenPosition = new(OperationStatusFlag.None, FeaturesResources.generated_code_is_overlapping_with_hidden_portion_of_the_code); public static readonly OperationStatus NoValidLocationToInsertMethodCall = new(OperationStatusFlag.None, FeaturesResources.No_valid_location_to_insert_method_call); public static readonly OperationStatus NoActiveStatement = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_no_active_statement); public static readonly OperationStatus ErrorOrUnknownType = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_an_error_or_unknown_type); public static readonly OperationStatus UnsafeAddressTaken = new(OperationStatusFlag.BestEffort, FeaturesResources.The_address_of_a_variable_is_used_inside_the_selected_code); public static readonly OperationStatus LocalFunctionCallWithoutDeclaration = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_a_local_function_call_without_its_declaration); /// <summary> /// create operation status with the given data /// </summary> public static OperationStatus<T> Create<T>(OperationStatus status, T data) => new(status, data); } }
// 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.ExtractMethod { internal partial class OperationStatus { public static readonly OperationStatus Succeeded = new(OperationStatusFlag.Succeeded, reason: null); public static readonly OperationStatus FailedWithUnknownReason = new(OperationStatusFlag.None, reason: FeaturesResources.Unknown_error_occurred); public static readonly OperationStatus OverlapsHiddenPosition = new(OperationStatusFlag.None, FeaturesResources.generated_code_is_overlapping_with_hidden_portion_of_the_code); public static readonly OperationStatus NoValidLocationToInsertMethodCall = new(OperationStatusFlag.None, FeaturesResources.No_valid_location_to_insert_method_call); public static readonly OperationStatus NoActiveStatement = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_no_active_statement); public static readonly OperationStatus ErrorOrUnknownType = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_an_error_or_unknown_type); public static readonly OperationStatus UnsafeAddressTaken = new(OperationStatusFlag.BestEffort, FeaturesResources.The_address_of_a_variable_is_used_inside_the_selected_code); public static readonly OperationStatus LocalFunctionCallWithoutDeclaration = new(OperationStatusFlag.BestEffort, FeaturesResources.The_selection_contains_a_local_function_call_without_its_declaration); /// <summary> /// create operation status with the given data /// </summary> public static OperationStatus<T> Create<T>(OperationStatus status, T data) => new(status, data); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/CSharpTest2/Recommendations/LetKeywordRecommenderTests.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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class LetKeywordRecommenderTests : 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 TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLet() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y let $$")); } } }
// 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 Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class LetKeywordRecommenderTests : 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 TestNotAtEndOfPreviousClause() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNewClause() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousContinuationClause() { await VerifyKeywordAsync(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBetweenClauses() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLet() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y let $$")); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/TestUtilities/AutomaticCompletion/AbstractAutomaticLineEnderTests.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.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<T>(); } }
// 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.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion { [UseExportProvider] public abstract class AbstractAutomaticLineEnderTests { protected abstract string Language { get; } protected abstract Action CreateNextHandler(TestWorkspace workspace); internal abstract IChainedCommandHandler<AutomaticLineEnderCommandArgs> GetCommandHandler(TestWorkspace workspace); protected void Test(string expected, string markupCode, bool completionActive = false, bool assertNextHandlerInvoked = false) { TestFileMarkupParser.GetPositionsAndSpans(markupCode, out var code, out var positions, out _); Assert.NotEmpty(positions); foreach (var position in positions) { // Run the test once for each input position. All marked positions in the input for a test are expected // to have the same result. Test(expected, code, position, completionActive, assertNextHandlerInvoked); } } #pragma warning disable IDE0060 // Remove unused parameter - https://github.com/dotnet/roslyn/issues/45892 private void Test(string expected, string code, int position, bool completionActive = false, bool assertNextHandlerInvoked = false) #pragma warning restore IDE0060 // Remove unused parameter { var markupCode = code[0..position] + "$$" + code[position..]; // WPF is required for some reason: https://github.com/dotnet/roslyn/issues/46286 using var workspace = TestWorkspace.Create(Language, compilationOptions: null, parseOptions: null, new[] { markupCode }, composition: EditorTestCompositions.EditorFeaturesWpf); var view = workspace.Documents.Single().GetTextView(); var buffer = workspace.Documents.Single().GetTextBuffer(); var nextHandlerInvoked = false; view.Caret.MoveTo(new SnapshotPoint(buffer.CurrentSnapshot, workspace.Documents.Single(d => d.CursorPosition.HasValue).CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var nextHandler = assertNextHandlerInvoked ? () => nextHandlerInvoked = true : CreateNextHandler(workspace); commandHandler.ExecuteCommand(new AutomaticLineEnderCommandArgs(view, buffer), nextHandler, TestCommandExecutionContext.Create()); Test(view, buffer, expected); Assert.Equal(assertNextHandlerInvoked, nextHandlerInvoked); } private static void Test(ITextView view, ITextBuffer buffer, string expectedWithAnnotations) { MarkupTestFile.GetPosition(expectedWithAnnotations, out var expected, out int expectedPosition); // Remove any virtual space from the expected text. var virtualPosition = view.Caret.Position.VirtualBufferPosition; expected = expected.Remove(virtualPosition.Position, virtualPosition.VirtualSpaces); Assert.Equal(expected, buffer.CurrentSnapshot.GetText()); Assert.Equal(expectedPosition, virtualPosition.Position.Position + virtualPosition.VirtualSpaces); } public static T GetService<T>(TestWorkspace workspace) => workspace.GetService<T>(); public static T GetExportedValue<T>(TestWorkspace workspace) => workspace.ExportProvider.GetExportedValue<T>(); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/Core/Host/IWaitIndicator.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.Editor.Host { [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this. If you have a MEF implementation, you can delete it.")] internal interface IWaitIndicator { /// <summary> /// Schedule the action on the caller's thread and wait for the task to complete. /// </summary> WaitIndicatorResult Wait(string title, string message, bool allowCancel, bool showProgress, Action<IWaitContext> action); IWaitContext StartWait(string title, string message, bool allowCancel, bool showProgress); } [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this.")] internal static class IWaitIndicatorExtensions { [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this.")] public static WaitIndicatorResult Wait( this IWaitIndicator waitIndicator, string title, string message, bool allowCancel, Action<IWaitContext> action) { return waitIndicator.Wait(title, message, allowCancel, showProgress: false, action: action); } } }
// 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.Editor.Host { [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this. If you have a MEF implementation, you can delete it.")] internal interface IWaitIndicator { /// <summary> /// Schedule the action on the caller's thread and wait for the task to complete. /// </summary> WaitIndicatorResult Wait(string title, string message, bool allowCancel, bool showProgress, Action<IWaitContext> action); IWaitContext StartWait(string title, string message, bool allowCancel, bool showProgress); } [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this.")] internal static class IWaitIndicatorExtensions { [Obsolete("You should now use IUIThreadOperationExecutor, which is a platform supported version of this.")] public static WaitIndicatorResult Wait( this IWaitIndicator waitIndicator, string title, string message, bool allowCancel, Action<IWaitContext> action) { return waitIndicator.Wait(title, message, allowCancel, showProgress: false, action: action); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpBuild.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.Diagnostics; using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpBuild : AbstractIntegrationTest { public CSharpBuild(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution(nameof(CSharpBuild)); VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project("TestProj"), WellKnownProjectTemplates.ConsoleApplication, LanguageNames.CSharp); } [WpfFact, Trait(Traits.Feature, Traits.Features.Build)] public void BuildProject() { var editorText = @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; VisualStudio.Editor.SetText(editorText); // TODO: Validate build works as expected } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/18204"), Trait(Traits.Feature, Traits.Features.Build)] public void BuildWithCommandLine() { VisualStudio.SolutionExplorer.SaveAll(); var pathToDevenv = Path.Combine(VisualStudio.InstallationPath, @"Common7\IDE\devenv.exe"); var pathToSolution = VisualStudio.SolutionExplorer.SolutionFileFullPath; var logFileName = pathToSolution + ".log"; File.Delete(logFileName); var commandLine = $"\"{pathToSolution}\" /Rebuild Debug /Out \"{logFileName}\" {VisualStudioInstanceFactory.VsLaunchArgs}"; var process = Process.Start(pathToDevenv, commandLine); Assert.True(process.WaitForExit((int)Helper.HangMitigatingTimeout.TotalMilliseconds)); Assert.Contains("Rebuild All: 1 succeeded, 0 failed, 0 skipped", File.ReadAllText(logFileName)); Assert.Equal(0, process.ExitCode); } } }
// 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.Diagnostics; using System.IO; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpBuild : AbstractIntegrationTest { public CSharpBuild(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution(nameof(CSharpBuild)); VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project("TestProj"), WellKnownProjectTemplates.ConsoleApplication, LanguageNames.CSharp); } [WpfFact, Trait(Traits.Feature, Traits.Features.Build)] public void BuildProject() { var editorText = @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } }"; VisualStudio.Editor.SetText(editorText); // TODO: Validate build works as expected } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/18204"), Trait(Traits.Feature, Traits.Features.Build)] public void BuildWithCommandLine() { VisualStudio.SolutionExplorer.SaveAll(); var pathToDevenv = Path.Combine(VisualStudio.InstallationPath, @"Common7\IDE\devenv.exe"); var pathToSolution = VisualStudio.SolutionExplorer.SolutionFileFullPath; var logFileName = pathToSolution + ".log"; File.Delete(logFileName); var commandLine = $"\"{pathToSolution}\" /Rebuild Debug /Out \"{logFileName}\" {VisualStudioInstanceFactory.VsLaunchArgs}"; var process = Process.Start(pathToDevenv, commandLine); Assert.True(process.WaitForExit((int)Helper.HangMitigatingTimeout.TotalMilliseconds)); Assert.Contains("Rebuild All: 1 succeeded, 0 failed, 0 skipped", File.ReadAllText(logFileName)); Assert.Equal(0, process.ExitCode); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Test/Semantic/Semantics/OutVarTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using static Roslyn.Test.Utilities.TestMetadata; using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.OutVar)] public class OutVarTests : CompilingTestBase { [Fact] public void OldVersion() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")] [WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")] public void DiagnosticsDifferenceBetweenLanguageVersions_01() { var text = @" public class Cls { public static void Test1() { Test(out int x1); } public static void Test2() { var x = new Cls(out int x2); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test(out int x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22), // (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33), // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_01() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_02() { var text = @" public class Cls { public static void Main() { Test1(out (var x1, var x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_03() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, long x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,28): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_04() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, (long x2, byte x3))); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,29): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29), // (6,38): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38), // (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,29): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29), // (6,38): error CS0165: Use of unassigned local variable 'x3' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_05() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2, x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_06() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; Test1(out var (x1)); System.Console.WriteLine(F1); } static ref int var(object x) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_07() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, x2: x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2: x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_08() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (ref x1, x2)); System.Console.WriteLine(F1); } static ref int var(ref object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (ref x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_09() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, (x2))); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_10() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var ((x1), x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var ((x1), x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_11() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_12() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out M1 (x1, x2)); System.Console.WriteLine(F1); } static ref int M1(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_13() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(ref var (x1, x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(ref int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(ref var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_14() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(var (x1, x2)); System.Console.WriteLine(F1); } static int var(object x1, object x2) { F1 = 123; return 124; } static object Test1(int x) { System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"124 123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_15() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out M1 (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int M1(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_16() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (a: x2, b: x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (a: x2, b: x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == name); } private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name) { return GetDeclarations(tree, name).Single(); } internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name) { return GetOutVarDeclarations(tree, name).Single(); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration()); } [Fact] public void Simple_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); int x2; Test3(out x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references); } private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references); } internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode( SemanticModel model, DeclarationExpressionSyntax decl, IdentifierNameSyntax reference) { VerifyModelForOutVar( model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: reference); } private static void VerifyModelForOutVar( SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, bool isShadowed, bool verifyDataFlow = true, LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax); Assert.NotNull(symbol); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.False(((ILocalSymbol)symbol).IsFixed); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single(); if (isShadowed) { Assert.NotEqual(symbol, other); } else { Assert.Same(symbol, other); } Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type); foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } if (verifyDataFlow) { VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol); } } private static void AssertInfoForDeclarationExpressionSyntax( SemanticModel model, DeclarationExpressionSyntax decl, ISymbol expectedSymbol = null, ITypeSymbol expectedType = null ) { var symbolInfo = model.GetSymbolInfo(decl); Assert.Equal(expectedSymbol, symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl)); var typeInfo = model.GetTypeInfo(decl); Assert.Equal(expectedType, typeInfo.Type); // skip cases where operation is not supported AssertTypeFromOperation(model, expectedType, decl); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.Equal(expectedType, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl)); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.True(model.GetConversion(decl).IsIdentity); var typeSyntax = decl.Type; Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax)); Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax)); ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType(); if (expected?.IsErrorType() != false) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol); } typeInfo = model.GetTypeInfo(typeSyntax); Assert.Equal(expected, typeInfo.Type); Assert.Equal(expected, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax)); Assert.True(model.GetConversion(typeSyntax).IsIdentity); var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false); Assert.False(conversion.Exists); Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Null(model.GetDeclaredSymbol(decl)); } private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl) { // see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail // unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode. // what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from // error recovery mode var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault(); if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true) { // invalid syntax case where operation is not supported return; } Assert.Equal(expectedType, model.GetOperation(decl)?.Type); } private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol) { var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax; if (dataFlowParent == null) { if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax)) { Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent); } return; } if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); return; } var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (isExecutableCode) { Assert.True(dataFlow.Succeeded); Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); if (!isDelegateCreation) { Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); var flowsIn = FlowsIn(dataFlowParent, decl, references); Assert.Equal(flowsIn, dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(flowsIn, dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(FlowsOut(dataFlowParent, decl, references), dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(ReadOutside(dataFlowParent, references), dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(WrittenOutside(dataFlowParent, references), dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type); } private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; Assert.NotEqual(SymbolKind.Field, symbol.Kind); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; if (symbol.Kind == SymbolKind.Local) { var local = symbol.GetSymbol<SourceLocalSymbol>(); var parent = local.IdentifierToken.Parent; Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration())); if (parent.Kind() == SyntaxKind.VariableDeclarator) { var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent; switch (parent1.Kind()) { case SyntaxKind.FixedStatement: case SyntaxKind.ForStatement: case SyntaxKind.UsingStatement: break; default: Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind()); break; } } } Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl) { return (SingleVariableDesignationSyntax)decl.Designation; } private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart) { if (IsRead(reference)) { return true; } } } return false; } private static bool IsRead(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left != reference) { return true; } break; default: return true; } return false; } private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsRead(reference)) { return true; } } } return false; } private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { ForStatementSyntax forStatement; if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null && forStatement.Incrementors.Span.Contains(decl.Position) && forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null)) { return false; } var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault(); var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax); MethodDeclarationSyntax methodDeclParent; if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" && ((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null || methodDeclParent.Body.Statements.First() != containingReturnOrThrow)) { return false; } foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span) && (containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) && (reference.SpanStart > decl.SpanStart || (containingReturnOrThrow == null && reference.Ancestors().OfType<DoStatementSyntax>().Join( decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any()))) { if (IsRead(reference)) { return true; } } } return false; } private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsWrite(reference)) { return true; } } } return false; } private static bool IsWrite(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left == reference) { return true; } break; case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.PostDecrementExpression: return true; default: return false; } return false; } [Fact] public void Simple_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Int32 x1), x1); int x2 = 0; Test3(x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_03() { var text = @" public class Cls { public static void Main() { Test2(Test1(out (int, int) x1), x1); } static object Test1(out (int, int) x) { x = (123, 124); return null; } static void Test2(object x, (int, int) y) { System.Console.WriteLine(y); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_04() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1); } static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = new System.Collections.Generic.List<System.Int32>(); return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, out x1), x1); } static object Test1(out int x, out int y) { x = 123; y = 124; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, x1 = 124), x1); } static object Test1(out int x, int y) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_07() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1, x1 = 124); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y, int z) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_08() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), ref x1); int x2 = 0; Test3(ref x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, ref int y) { System.Console.WriteLine(y); } static void Test3(ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_09() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), out x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_10() { var text = @" public class Cls { public static void Main() { Test2(Test1(out dynamic x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_11() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int[] x1), x1); } static object Test1(out int[] x) { x = new [] {123}; return null; } static void Test2(object x, int[] y) { System.Console.WriteLine(y[0]); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_01() { var text = @" public class Cls { public static void Main() { int x1 = 0; Test1(out int x1); Test2(Test1(out int x2), out int x2); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS0128: A local variable named 'x1' is already defined in this scope // Test1(out int x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23), // (9,29): error CS0128: A local variable named 'x2' is already defined in this scope // out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13) ); } [Fact] public void Scope_02() { var text = @" public class Cls { public static void Main() { Test2(x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15) ); } [Fact] public void Scope_03() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_04() { var text = @" public class Cls { public static void Main() { Test1(out int x1); System.Console.WriteLine(x1); } static object Test1(out int x) { x = 1; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_05() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out var x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_Attribute_01() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_02() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_03() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_04() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void AttributeArgument_01() { var source = @" public class X { [Test(out var x3)] [Test(out int x4)] [Test(p: out var x5)] [Test(p: out int x6)] public static void Main() { } } class Test : System.Attribute { public Test(out int p) { p = 100; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (4,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out var x3)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11), // (4,19): error CS1003: Syntax error, ',' expected // [Test(out var x3)] Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19), // (5,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out int x4)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11), // (5,15): error CS1525: Invalid expression term 'int' // [Test(out int x4)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15), // (5,19): error CS1003: Syntax error, ',' expected // [Test(out int x4)] Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19), // (6,14): error CS1525: Invalid expression term 'out' // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14), // (6,14): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18), // (6,22): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22), // (7,14): error CS1525: Invalid expression term 'out' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14), // (7,14): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14), // (7,18): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18), // (7,18): error CS1525: Invalid expression term 'int' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22), // (4,15): error CS0103: The name 'var' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15), // (4,19): error CS0103: The name 'x3' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19), // (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out var x3)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6), // (5,19): error CS0103: The name 'x4' does not exist in the current context // [Test(out int x4)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19), // (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out int x4)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6), // (6,18): error CS0103: The name 'var' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18), // (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18), // (6,22): error CS0103: The name 'x5' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22), // (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6), // (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18), // (7,22): error CS0103: The name 'x6' does not exist in the current context // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22), // (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6) ); var tree = compilation.SyntaxTrees.Single(); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); Assert.False(GetOutVarDeclarations(tree, "x4").Any()); Assert.False(GetOutVarDeclarations(tree, "x5").Any()); Assert.False(GetOutVarDeclarations(tree, "x6").Any()); } [Fact] public void Scope_Catch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } } void Test4() { var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Scope_Catch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out int x1) && x1 > 0) { Dummy(x1); } } void Test4() { int x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out int x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out int x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out int x7) && x7 > 0) { int x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out int x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out int x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out int x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out int x10)) { int y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out int x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out int x14), TakeOutParam(out int x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out int x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out int x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out int x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out int x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out int x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Catch_01_ExplicitType() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Scope_ConstructorInitializers_01() { var source = @" public class X { public static void Main() { } X(byte x) : this(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : this(x4 && TakeOutParam(4, out int x4)) {} X(short x) : this(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : this(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : this(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : this(x7, 2) {} void Test73() { Dummy(x7, 3); } X(params object[] x) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : this(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : this(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_02() { var source = @" public class X : Y { public static void Main() { } X(byte x) : base(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : base(x4 && TakeOutParam(4, out int x4)) {} X(short x) : base(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : base(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : base(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : base(x7, 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } public class Y { public Y(params object[] x) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : base(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : base(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_03() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D { public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_04() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D : C { public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_05() { var source = @"using System; class D { public D(int o) : this(SpeculateHere) { } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_06() { var source = @"using System; class D : C { public D(int o) : base(SpeculateHere) { } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var initializerOperation = model.GetOperation(initializer); Assert.Null(initializerOperation.Parent.Parent.Parent); VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Expression: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)') Children(1): IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5') IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5') Left: IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o') IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5') Left: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] public void Scope_ConstructorInitializers_07() { var source = @" public class X : Y { public static void Main() { } X(byte x3) : base(TakeOutParam(3, out var x3)) {} X(sbyte x) : base(TakeOutParam(4, out var x4)) { int x4 = 1; System.Console.WriteLine(x4); } X(ushort x) : base(TakeOutParam(51, out var x5)) => Dummy(TakeOutParam(52, out var x5), x5); X(short x) : base(out int x6, x6) {} X(uint x) : base(out var x7, x7) {} X(int x) : base(TakeOutParam(out int x8, x8)) {} X(ulong x) : base(TakeOutParam(out var x9, x9)) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } public class Y { public Y(params object[] x) {} public Y(out int x, int y) { x = y; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : base(TakeOutParam(3, out var x3)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40), // (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x4 = 1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13), // (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // => Dummy(TakeOutParam(52, out var x5), x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39), // (24,28): error CS0165: Use of unassigned local variable 'x6' // : base(out int x6, x6) Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28), // (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list. // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28), // (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20), // (32,41): error CS0165: Use of unassigned local variable 'x8' // : base(TakeOutParam(out int x8, x8)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41), // (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list. // : base(TakeOutParam(out var x9, x9)) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").Single(); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref); } [Fact] public void Scope_Do_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { do { Dummy(x1); } while (TakeOutParam(true, out var x1) && x1); } void Test2() { do Dummy(x2); while (TakeOutParam(true, out var x2) && x2); } void Test4() { var x4 = 11; Dummy(x4); do Dummy(x4); while (TakeOutParam(true, out var x4) && x4); } void Test6() { do Dummy(x6); while (x6 && TakeOutParam(true, out var x6)); } void Test7() { do { var x7 = 12; Dummy(x7); } while (TakeOutParam(true, out var x7) && x7); } void Test8() { do Dummy(x8); while (TakeOutParam(true, out var x8) && x8); System.Console.WriteLine(x8); } void Test9() { do { Dummy(x9); do Dummy(x9); while (TakeOutParam(true, out var x9) && x9); // 2 } while (TakeOutParam(true, out var x9) && x9); } void Test10() { do { var y10 = 12; Dummy(y10); } while (TakeOutParam(y10, out var x10)); } //void Test11() //{ // do // { // let y11 = 12; // Dummy(y11); // } // while (TakeOutParam(y11, out var x11)); //} void Test12() { do var y12 = 12; while (TakeOutParam(y12, out var x12)); } //void Test13() //{ // do // let y13 = 12; // while (TakeOutParam(y13, out var x13)); //} void Test14() { do { Dummy(x14); } while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13), // (14,19): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19), // (22,19): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19), // (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43), // (32,19): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy(x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19), // (40,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16), // (39,19): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19), // (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17), // (56,19): error CS0841: Cannot use local variable 'x8' before it is declared // Dummy(x8); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19), // (59,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34), // (66,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19), // (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9); // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47), // (68,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23), // (81,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29), // (98,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29), // (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17), // (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46), // (112,19): error CS0841: Cannot use local variable 'x14' before it is declared // Dummy(x14); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[1]); VerifyNotAnOutLocal(model, x7Ref[0]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[1]); VerifyNotAnOutLocal(model, y10Ref[0]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Do_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) do { } while (TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Do_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@" do {} while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { int f = 1; do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false); if (f) { do ; while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { } bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0; bool Test4(object o) => x4 && TakeOutParam(o, out int x4); bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0; void Test72() => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test11(object x11) => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,29): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4(object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29), // (13,67): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67), // (19,28): error CS0103: The name 'x7' does not exist in the current context // void Test72() => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool Test11(object x11) => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")] public void Scope_ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test3() { bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0; f(null); } void Test4() { bool f (object o) => x4 && TakeOutParam(o, out int x4); f(null); } void Test5() { bool f (object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; f(null, null); } void Test6() { bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0; f1(null); f2(null); } void Test7() { Dummy(x7, 1); bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0; Dummy(x7, 2); f(null); } void Test11() { var x11 = 11; Dummy(x11); bool f (object o) => TakeOutParam(o, out int x11) && x11 > 0; f(null); } void Test12() { bool f (object o) => TakeOutParam(o, out int x12) && x12 > 0; var x12 = 11; Dummy(x12); f(null); } System.Action Test13() { return () => { bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0; f(null); }; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15), // (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54), // (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); // Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214 var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").Single(); VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref); } [Fact] public void ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out int x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedLocalFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out var x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void Scope_ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { } bool Test3 => TakeOutParam(3, out int x3) && x3 > 0; bool Test4 => x4 && TakeOutParam(4, out int x4); bool Test5 => TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0; bool Test71 => TakeOutParam(7, out int x7) && x7 > 0; bool Test72 => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool this[object x11] => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,19): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 => x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19), // (13,44): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44), // (19,26): error CS0103: The name 'x7' does not exist in the current context // bool Test72 => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool this[object x11] => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void ExpressionBodiedProperties_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void Scope_ExpressionStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { Dummy(TakeOutParam(true, out var x1), x1); { Dummy(TakeOutParam(true, out var x1), x1); } Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ExpressionStatement_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) Test2(Test1(out int x1), x1); if (test) { Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_ExpressionStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ExpressionStatement_04() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Scope_FieldInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 = x4 && TakeOutParam(4, out int x4); bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,57): error CS0103: The name 'x8' does not exist in the current context // bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57), // (23,19): error CS0103: The name 'x9' does not exist in the current context // bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReference(tree, "x8"); VerifyModelForOutVar(model, x8Decl); VerifyNotInScope(model, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReference(tree, "x9"); VerifyNotInScope(model, x9Ref); VerifyModelForOutVar(model, x9Decl); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_FieldInitializers_02() { var source = @"using static Test; public enum X { Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0, Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Test72 = x7, } class Test { public static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'x4' before it is declared // Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13), // (9,38): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38), // (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant // Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13), // (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14), // (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70), // (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant // Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14), // (15,14): error CS0103: The name 'x7' does not exist in the current context // Test72 = x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14), // (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant // Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0') Locals: Local_1: System.Int32 x3 IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0') Condition: IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_FieldInitializers_03() { var source = @" public class X { public static void Main() { } const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; const bool Test4 = x4 && TakeOutParam(4, out int x4); const bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; const bool Test72 = x7 > 2; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant // const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24), // (10,24): error CS0841: Cannot use local variable 'x4' before it is declared // const bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24), // (13,49): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49), // (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant // const bool Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("X.Test5").WithLocation(12, 24), // (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25), // (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73), // (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant // const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25), // (19,25): error CS0103: The name 'x7' does not exist in the current context // const bool Test72 = x7 > 2; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_FieldInitializers_04() { var source = @" class X : Y { public static void Main() { } bool Test3 = TakeOutParam(out int x3, x3); bool Test4 = TakeOutParam(out var x4, x4); bool Test5 = TakeOutParam(out int x5, 5); X() : this(x5) { System.Console.WriteLine(x5); } X(object x) : base(x5) => System.Console.WriteLine(x5); static bool Test6 = TakeOutParam(out int x6, 6); static X() { System.Console.WriteLine(x6); } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } class Y { public Y(object y) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,43): error CS0165: Use of unassigned local variable 'x3' // bool Test3 = TakeOutParam(out int x3, x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43), // (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list. // bool Test4 = TakeOutParam(out var x4, x4); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43), // (15,12): error CS0103: The name 'x5' does not exist in the current context // : this(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12), // (17,34): error CS0103: The name 'x5' does not exist in the current context // System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34), // (21,12): error CS0103: The name 'x5' does not exist in the current context // : base(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12), // (22,33): error CS0103: The name 'x5' does not exist in the current context // => System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33), // (27,34): error CS0103: The name 'x6' does not exist in the current context // System.Console.WriteLine(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(4, x5Ref.Length); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); VerifyNotInScope(model, x5Ref[3]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void FieldInitializers_05() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,54): error CS0165: Use of unassigned local variable 'x1' // bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void FieldInitializers_06() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void Scope_Fixed_01() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p = Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // fixed (int* p = Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { fixed (int* p = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Fixed_02() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* x1 = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2), x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p = Dummy(TakeOutParam(true, out var x3) && x3)) { Dummy(x3); } } void Test4() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4), p2 = Dummy(TakeOutParam(true, out var x4) && x4)) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (14,66): error CS0165: Use of unassigned local variable 'x1' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2 = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Fixed_02() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Scope_For_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for ( Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (; Dummy(TakeOutParam(true, out var x1) && x1) ;) { Dummy(x1); } } void Test2() { for (; Dummy(TakeOutParam(true, out var x2) && x2) ;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (; Dummy(TakeOutParam(true, out var x4) && x4) ;) Dummy(x4); } void Test6() { for (; Dummy(x6 && TakeOutParam(true, out var x6)) ;) Dummy(x6); } void Test7() { for (; Dummy(TakeOutParam(true, out var x7) && x7) ;) { var x7 = 12; Dummy(x7); } } void Test8() { for (; Dummy(TakeOutParam(true, out var x8) && x8) ;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (; Dummy(TakeOutParam(true, out var x9) && x9) ;) { Dummy(x9); for (; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;) Dummy(x9); } } void Test10() { for (; Dummy(TakeOutParam(y10, out var x10)) ;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (; // Dummy(TakeOutParam(y11, out var x11)) // ;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (; Dummy(TakeOutParam(y12, out var x12)) ;) var y12 = 12; } //void Test13() //{ // for (; // Dummy(TakeOutParam(y13, out var x13)) // ;) // let y13 = 12; //} void Test14() { for (; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_03() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(TakeOutParam(true, out var x1) && x1) ) { Dummy(x1); } } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2) ) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (;; Dummy(TakeOutParam(true, out var x4) && x4) ) Dummy(x4); } void Test6() { for (;; Dummy(x6 && TakeOutParam(true, out var x6)) ) Dummy(x6); } void Test7() { for (;; Dummy(TakeOutParam(true, out var x7) && x7) ) { var x7 = 12; Dummy(x7); } } void Test8() { for (;; Dummy(TakeOutParam(true, out var x8) && x8) ) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (;; Dummy(TakeOutParam(true, out var x9) && x9) ) { Dummy(x9); for (;; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ) Dummy(x9); } } void Test10() { for (;; Dummy(TakeOutParam(y10, out var x10)) ) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (;; // Dummy(TakeOutParam(y11, out var x11)) // ) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (;; Dummy(TakeOutParam(y12, out var x12)) ) var y12 = 12; } //void Test13() //{ // for (;; // Dummy(TakeOutParam(y13, out var x13)) // ) // let y13 = 12; //} void Test14() { for (;; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (16,19): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19), // (25,19): error CS0103: The name 'x2' does not exist in the current context // Dummy(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (44,19): error CS0103: The name 'x6' does not exist in the current context // Dummy(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19), // (63,19): error CS0103: The name 'x8' does not exist in the current context // Dummy(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (74,19): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19), // (78,23): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23), // (71,14): warning CS0162: Unreachable code detected // Dummy(TakeOutParam(true, out var x9) && x9) Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44), // (128,19): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref[0]); VerifyNotInScope(model, x2Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref[0]); VerifyNotInScope(model, x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0]); VerifyNotInScope(model, x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyNotInScope(model, x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyNotInScope(model, x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); VerifyNotInScope(model, x14Ref[1]); } [Fact] public void Scope_For_04() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (var b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (var b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (var b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (var b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (var b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (var b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (var b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (var b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (var b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (var b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (var b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (var b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_05() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (bool b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (bool b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (bool b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (bool b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (bool b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (bool b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (bool b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_06() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var x1 = Dummy(TakeOutParam(true, out var x1) && x1) ;;) {} } void Test2() { for (var x2 = true; Dummy(TakeOutParam(true, out var x2) && x2) ;) {} } void Test3() { for (var x3 = true;; Dummy(TakeOutParam(true, out var x3) && x3) ) {} } void Test4() { for (bool x4 = Dummy(TakeOutParam(true, out var x4) && x4) ;;) {} } void Test5() { for (bool x5 = true; Dummy(TakeOutParam(true, out var x5) && x5) ;) {} } void Test6() { for (bool x6 = true;; Dummy(TakeOutParam(true, out var x6) && x6) ) {} } void Test7() { for (bool x7 = true, b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) {} } void Test8() { for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8), b2 = Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2 = Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } void Test10() { for (var b = x10; Dummy(TakeOutParam(true, out var x10) && x10) && Dummy(TakeOutParam(true, out var x10) && x10); Dummy(TakeOutParam(true, out var x10) && x10)) {} } void Test11() { for (bool b = x11; Dummy(TakeOutParam(true, out var x11) && x11) && Dummy(TakeOutParam(true, out var x11) && x11); Dummy(TakeOutParam(true, out var x11) && x11)) {} } void Test12() { for (Dummy(x12); Dummy(x12) && Dummy(TakeOutParam(true, out var x12) && x12); Dummy(TakeOutParam(true, out var x12) && x12)) {} } void Test13() { for (var b = x13; Dummy(x13); Dummy(TakeOutParam(true, out var x13) && x13), Dummy(TakeOutParam(true, out var x13) && x13)) {} } void Test14() { for (bool b = x14; Dummy(x14); Dummy(TakeOutParam(true, out var x14) && x14), Dummy(TakeOutParam(true, out var x14) && x14)) {} } void Test15() { for (Dummy(x15); Dummy(x15); Dummy(x15), Dummy(TakeOutParam(true, out var x15) && x15)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47), // (13,54): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54), // (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x2) && x2) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47), // (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used // for (var x2 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3) && x3) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used // for (var x3 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18), // (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47), // (37,54): error CS0165: Use of unassigned local variable 'x4' // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54), // (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x5) && x5) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47), // (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used // for (bool x5 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19), // (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x6) && x6) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47), // (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used // for (bool x6 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19), // (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47), // (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2 = Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52), // (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47), // (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47), // (77,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23), // (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47), // (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47), // (86,22): error CS0103: The name 'x10' does not exist in the current context // for (var b = x10; Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22), // (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope // Dummy(TakeOutParam(true, out var x10) && x10); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47), // (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x10) && x10)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47), // (95,23): error CS0103: The name 'x11' does not exist in the current context // for (bool b = x11; Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23), // (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope // Dummy(TakeOutParam(true, out var x11) && x11); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47), // (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x11) && x11)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47), // (104,20): error CS0103: The name 'x12' does not exist in the current context // for (Dummy(x12); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20), // (105,20): error CS0841: Cannot use local variable 'x12' before it is declared // Dummy(x12) && Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20), // (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x12) && x12)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47), // (113,22): error CS0103: The name 'x13' does not exist in the current context // for (var b = x13; Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22), // (114,20): error CS0103: The name 'x13' does not exist in the current context // Dummy(x13); Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20), // (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope // Dummy(TakeOutParam(true, out var x13) && x13)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47), // (122,23): error CS0103: The name 'x14' does not exist in the current context // for (bool b = x14; Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23), // (123,20): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20), // (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope // Dummy(TakeOutParam(true, out var x14) && x14)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47), // (131,20): error CS0103: The name 'x15' does not exist in the current context // for (Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20), // (132,20): error CS0103: The name 'x15' does not exist in the current context // Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20), // (133,20): error CS0841: Cannot use local variable 'x15' before it is declared // Dummy(x15), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(3, x10Decl.Length); Assert.Equal(4, x10Ref.Length); VerifyNotInScope(model, x10Ref[0]); VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]); VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]); var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Decl.Length); Assert.Equal(4, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]); VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]); var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Decl.Length); Assert.Equal(4, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]); VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(4, x13Ref.Length); VerifyNotInScope(model, x13Ref[0]); VerifyNotInScope(model, x13Ref[1]); VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyNotInScope(model, x14Ref[0]); VerifyNotInScope(model, x14Ref[1]); VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(4, x15Ref.Length); VerifyNotInScope(model, x15Ref[0]); VerifyNotInScope(model, x15Ref[1]); VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]); } [Fact] public void Scope_For_07() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(x1), Dummy(TakeOutParam(true, out var x1) && x1)) {} } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2), Dummy(TakeOutParam(true, out var x2) && x2)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,20): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20), // (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2) && x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_06() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1))) { x0++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"20 30 -- 20 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_07() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 -- 10 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Foreach_01() { var source = @" public class X { public static void Main() { } System.Collections.IEnumerable Dummy(params object[] x) {return null;} void Test1() { foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } void Test15() { foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60), // (35,33): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65), // (68,46): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46), // (86,46): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,57): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57), // (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_If_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (TakeOutParam(true, out var x1)) { Dummy(x1); } else { System.Console.WriteLine(x1); } } void Test2() { if (TakeOutParam(true, out var x2)) Dummy(x2); else System.Console.WriteLine(x2); } void Test3() { if (TakeOutParam(true, out var x3)) Dummy(x3); else { var x3 = 12; System.Console.WriteLine(x3); } } void Test4() { var x4 = 11; Dummy(x4); if (TakeOutParam(true, out var x4)) Dummy(x4); } void Test5(int x5) { if (TakeOutParam(true, out var x5)) Dummy(x5); } void Test6() { if (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { if (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { if (TakeOutParam(true, out var x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { if (TakeOutParam(true, out var x9)) { Dummy(x9); if (TakeOutParam(true, out var x9)) // 2 Dummy(x9); } } void Test10() { if (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } void Test12() { if (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // if (TakeOutParam(y13, out var x13)) // let y13 = 12; //} static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13), // (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x3 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17), // (46,40): error CS0128: A local variable named 'x4' is already defined in this scope // if (TakeOutParam(true, out var x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40), // (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x5)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40), // (58,13): error CS0841: Cannot use local variable 'x6' before it is declared // if (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13), // (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17), // (83,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19), // (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44), // (91,26): error CS0103: The name 'y10' does not exist in the current context // if (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26), // (100,26): error CS0103: The name 'y12' does not exist in the current context // if (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26), // (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); } [Fact] public void Scope_If_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) if (TakeOutParam(true, out var x1)) { } else { } x1++; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_If_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@" if (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, TakeOutParam(val, out var x1), x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) ; if (f) { if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_Lambda_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} System.Action<object> Test1() { return (o) => let x1 = o; } System.Action<object> Test2() { return (o) => let var x2 = o; } void Test3() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0)); } void Test4() { Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); } void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0)); } void Test6() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0)); } void Test7() { Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0), x7); Dummy(x7, 2); } void Test8() { Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8)); } void Test9() { Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && x9 > 0), x9); } void Test10() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && x10 > 0), TakeOutParam(true, out var x10), x10); } void Test11() { var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && x11 > 0), x11); } void Test12() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73), // (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73), // (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73), // (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { var d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { var d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // var d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // var d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); object d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { object d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { object d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { object d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,53): error CS0128: A local variable named 'x4' is already defined in this scope // object d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53), // (24,26): error CS0841: Cannot use local variable 'x6' before it is declared // object d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26), // (36,50): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var x1 = Dummy(TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { object x2 = Dummy(TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] public void Scope_LocalDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Scope_LocalDeclarationStmt_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y1 = Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] public void Scope_LocalDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d =TakeOutParam(true, out var x1) && x1 != null; x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (d, dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var (d, dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { var (d, dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var (d, dd, ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,51): error CS0128: A local variable named 'x4' is already defined in this scope // var (d, dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51), // (24,24): error CS0841: Cannot use local variable 'x6' before it is declared // var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); (object d, object dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { (object d, object dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { (object d, object dd, object ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,61): error CS0128: A local variable named 'x4' is already defined in this scope // (object d, object dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61), // (24,34): error CS0841: Cannot use local variable 'x6' before it is declared // (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (x1, dd) = (TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { (object x2, object dd) = (TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Dummy(x1)); Dummy(x1); } void Test2() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2), Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3), Dummy(x3)); } void Test4() { (object d1, object d2) = (Dummy(x4), Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,67): error CS0128: A local variable named 'x1' is already defined in this scope // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67), // (12,72): error CS0165: Use of unassigned local variable 'x1' // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,41): error CS0841: Cannot use local variable 'x4' before it is declared // (object d1, object d2) = (Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyNotAnOutLocal(model, x1Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_05() { var source = @" public class X { public static void Main() { } void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" var (y1, dd) = (TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var (d, dd) = (TakeOutParam(true, out var x1), x1); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] public void Scope_Lock_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { lock (Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { lock (Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Dummy(x4); } void Test6() { lock (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { lock (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { lock (Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { lock (Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { lock (Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // lock (Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { lock (Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // lock (Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { lock (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,48): error CS0128: A local variable named 'x4' is already defined in this scope // lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48), // (35,21): error CS0841: Cannot use local variable 'x6' before it is declared // lock (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (60,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19), // (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52), // (68,34): error CS0103: The name 'y10' does not exist in the current context // lock (Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34), // (86,34): error CS0103: The name 'y12' does not exist in the current context // lock (Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,45): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Lock_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { if (true) lock (Dummy(TakeOutParam(true, out var x1))) { } x1++; } static object TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (17,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Lock_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@" lock (Dummy(TakeOutParam(true, out var x1), x1)) ; "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(TakeOutParam(""lock"", out var x1), x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_ParameterDefault_01() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out int x4)) {} void Test5(bool p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0') Locals: Local_1: System.Int32 x3 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0') Left: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_ParameterDefault_02() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out var x4)) {} void Test5(bool p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out var x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_PropertyInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); bool Test5 {get;} = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 {get;} = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,25): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,32): error CS0103: The name 'x7' does not exist in the current context // bool Test72 {get;} = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_03() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,63): error CS0165: Use of unassigned local variable 'x1' // bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void PropertyInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(new X().Test1); } int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Scope_Query_01() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); } void Test2() { var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); } void Test3() { var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); } void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } void Test6() { var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); } void Test7() { var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); } void Test8() { var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); } void Test9() { var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); } void Test10() { var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; } void Test11() { var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,26): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26), // (27,15): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15), // (35,32): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32), // (37,15): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15), // (45,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35), // (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35), // (49,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32), // (49,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36), // (52,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15), // (53,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15), // (61,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35), // (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35), // (66,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32), // (66,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36), // (69,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15), // (70,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15), // (78,26): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26), // (80,15): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15), // (87,27): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27), // (89,27): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27), // (91,26): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26), // (91,31): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31), // (93,15): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15), // (94,15): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15), // (102,15): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15), // (112,25): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25), // (109,25): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25), // (114,15): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15), // (115,15): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15), // (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24), // (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } [Fact] public void Scope_Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35), // (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35), // (22,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32), // (22,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36), // (25,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15), // (26,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15), // (35,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35), // (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35), // (40,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32), // (40,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36), // (43,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15), // (44,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0; var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0); Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62), // (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51), // (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58), // (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49), // (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51), // (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51), // (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47), // (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49), // (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54), // (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(3, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVarDuplicateInSameScope(model, yDecl); VerifyNotAnOutLocal(model, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); break; } VerifyNotAnOutLocal(model, yRef[2]); switch (i) { case 12: VerifyNotAnOutLocal(model, yRef[1]); break; default: VerifyNotAnOutLocal(model, yRef[1]); break; } } var y13Decl = GetOutVarDeclarations(tree, "y13").Single(); var y13Ref = GetReference(tree, "y13"); VerifyModelForOutVar(model, y13Decl, y13Ref); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_06() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y1), TakeOutParam(out int y2), TakeOutParam(out int y3), TakeOutParam(out int y4), TakeOutParam(out int y5), TakeOutParam(out int y6), TakeOutParam(out int y7), TakeOutParam(out int y8), TakeOutParam(out int y9), TakeOutParam(out int y10), TakeOutParam(out int y11), TakeOutParam(out int y12), from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62), // (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51), // (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58), // (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49), // (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51), // (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51), // (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47), // (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49), // (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54), // (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); break; case 12: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; default: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; } } } [Fact] public void Scope_Query_07() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y3), from x1 in new[] { 0 } select x1 into x1 join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on x1 equals x3 select y3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,62): error CS0128: A local variable named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); const string id = "y3"; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); // Since the name is declared twice in the same scope, // both references are to the same declaration. VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); } [Fact] public void Scope_Query_08() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4) ) ? 1 : 0} from y1 in new[] { 1 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by x1 into y4 select y4; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // from y1 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24), // (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24), // (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23), // (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 5; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_09() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by 1 into y4 select y4 == null ? 1 : 0 into x2 join y5 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4), TakeOutParam(out var y5) ) ? 1 : 0 } on x2 equals y5 select x2; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // var res = from y1 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24), // (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24), // (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23), // (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24), // (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5' // join y5 in new[] { Dummy(TakeOutParam(out var y1), Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 6; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); switch (i) { case 4: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; case 5: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; default: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; } } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] [WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")] public void Scope_Query_10() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } select y1; } void Test2() { var res = from y2 in new[] { 0 } join x3 in new[] { 1 } on TakeOutParam(out var y2) ? y2 : 0 equals x3 select y2; } void Test3() { var res = from x3 in new[] { 0 } join y3 in new[] { 1 } on x3 equals TakeOutParam(out var y3) ? y3 : 0 select y3; } void Test4() { var res = from y4 in new[] { 0 } where TakeOutParam(out var y4) && y4 == 1 select y4; } void Test5() { var res = from y5 in new[] { 0 } orderby TakeOutParam(out var y5) && y5 > 1, 1 select y5; } void Test6() { var res = from y6 in new[] { 0 } orderby 1, TakeOutParam(out var y6) && y6 > 1 select y6; } void Test7() { var res = from y7 in new[] { 0 } group TakeOutParam(out var y7) && y7 == 3 by y7; } void Test8() { var res = from y8 in new[] { 0 } group y8 by TakeOutParam(out var y8) && y8 == 3; } void Test9() { var res = from y9 in new[] { 0 } let x4 = TakeOutParam(out var y9) && y9 > 0 select y9; } void Test10() { var res = from y10 in new[] { 0 } select TakeOutParam(out var y10) && y10 > 0; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052 compilation.VerifyDiagnostics( // (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59), // (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(out var y2) ? y2 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48), // (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(out var y3) ? y3 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52), // (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(out var y4) && y4 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46), // (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(out var y5) && y5 > 1, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48), // (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(out var y6) && y6 > 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48), // (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(out var y7) && y7 == 3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46), // (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(out var y8) && y8 == 3; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43), // (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x4 = TakeOutParam(out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49), // (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(out var y10) && y10 > 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 11; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(i == 10 ? 1 : 2, yRef.Length); switch (i) { case 4: case 6: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; case 8: VerifyModelForOutVar(model, yDecl, yRef[1]); VerifyNotAnOutLocal(model, yRef[0]); break; case 10: VerifyModelForOutVar(model, yDecl, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; } } } [Fact] public void Scope_Query_11() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y1), from x2 in new [] { y1 } where TakeOutParam(x1, out var y1) select x2) select x1; } void Test2() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y2), TakeOutParam(x1 + 1, out var y2)) select x1; } void Test3() { var res = from x1 in new [] { 1 } where TakeOutParam(out int y3, y3) select x1; } void Test4() { var res = from x1 in new [] { 1 } where TakeOutParam(out var y4, y4) select x1; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x, int y) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(x1, out var y1) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62), // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray(); var y1Ref = GetReferences(tree, "y1").Single(); Assert.Equal(2, y1Decl.Length); VerifyModelForOutVar(model, y1Decl[0], y1Ref); VerifyModelForOutVar(model, y1Decl[1]); var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray(); Assert.Equal(2, y2Decl.Length); VerifyModelForOutVar(model, y2Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").Single(); VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").Single(); VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0} join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0} on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0 equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0 where TakeOutParam(6, out var y6) && Print(y6) orderby TakeOutParam(7, out var y7) && Print(y7), TakeOutParam(8, out var y8) && Print(y8) group TakeOutParam(9, out var y9) && Print(y9) by TakeOutParam(10, out var y10) && Print(y10) into g let x11 = TakeOutParam(11, out var y11) && Print(y11) select TakeOutParam(12, out var y12) && Print(y12); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl, yRef); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString()); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutVar(model, yDecl, yRef); } [Fact] public void Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in new[] { true } select a && TakeOutParam(3, out int x1) || x1 > 0; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,62): error CS0165: Use of unassigned local variable 'x1' // select a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); compilation.VerifyOperationTree(x1Decl, expectedOperationTree: @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') "); } [Fact] public void Query_04() { var source = @" using System.Linq; public class X { public static void Main() { System.Console.WriteLine(Test1()); } static int Test1() { var res = from a in new[] { 1 } select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; return res.Single(); } static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in (new[] { 1 }).AsQueryable() select TakeOutParam(a, out int x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,46): error CS8198: An expression tree may not contain an out argument variable declaration. // select TakeOutParam(a, out int x1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46) ); } [Fact] public void Scope_ReturnStatement_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) { return null; } object Test1() { return Dummy(TakeOutParam(true, out var x1), x1); { return Dummy(TakeOutParam(true, out var x1), x1); } return Dummy(TakeOutParam(true, out var x1), x1); } object Test2() { return Dummy(x2, TakeOutParam(true, out var x2)); } object Test3(int x3) { return Dummy(TakeOutParam(true, out var x3), x3); } object Test4() { var x4 = 11; Dummy(x4); return Dummy(TakeOutParam(true, out var x4), x4); } object Test5() { return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //object Test6() //{ // let x6 = 11; // Dummy(x6); // return Dummy(TakeOutParam(true, out var x6), x6); //} //object Test7() //{ // return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} object Test8() { return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } object Test9(bool y9) { if (y9) return Dummy(TakeOutParam(true, out var x9), x9); return null; } System.Func<object> Test10(bool y10) { return () => { if (y10) return Dummy(TakeOutParam(true, out var x10), x10); return null;}; } object Test11() { Dummy(x11); return Dummy(TakeOutParam(true, out var x11), x11); } object Test12() { return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53), // (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49), // (14,13): warning CS0162: Unreachable code detected // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13), // (21,22): error CS0841: Cannot use local variable 'x2' before it is declared // return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22), // (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49), // (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope // return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ReturnStatement_02() { var source = @" public class X { public static void Main() { } int Dummy(params object[] x) { return 0;} int Test1(bool val) { if (val) return Dummy(TakeOutParam(true, out var x1)); x1++; return 0; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ReturnStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@" return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(TakeOutParam(""return"", out var x1), x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static object Test(bool val) { if (val) return Dummy(TakeOutParam(""return 1"", out var x2), x2); if (!val) { return Dummy(TakeOutParam(""return 2"", out var x2), x2); } return null; } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return 1 return 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Switch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { switch (TakeOutParam(1, out var x1) ? x1 : 0) { case 0: Dummy(x1, 0); break; } Dummy(x1, 1); } void Test4() { var x4 = 11; Dummy(x4); switch (TakeOutParam(4, out var x4) ? x4 : 0) { case 4: Dummy(x4); break; } } void Test5(int x5) { switch (TakeOutParam(5, out var x5) ? x5 : 0) { case 5: Dummy(x5); break; } } void Test6() { switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) { case 6: Dummy(x6); break; } } void Test7() { switch (TakeOutParam(7, out var x7) ? x7 : 0) { case 7: var x7 = 12; Dummy(x7); break; } } void Test9() { switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 0); switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 1); break; } break; } } void Test10() { switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) { case 10: var y10 = 12; Dummy(y10); break; } } //void Test11() //{ // switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0)) // { // case 11: // let y11 = 12; // Dummy(y11); // break; // } //} void Test14() { switch (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ? 1 : 0) { case 0: Dummy(x14); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (27,41): error CS0128: A local variable named 'x4' is already defined in this scope // switch (TakeOutParam(4, out var x4) ? x4 : 0) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41), // (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(5, out var x5) ? x5 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41), // (47,17): error CS0841: Cannot use local variable 'x6' before it is declared // switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17), // (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21), // (71,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9, 0); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23), // (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(9, out var x9) ? x9 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49), // (85,17): error CS0103: The name 'y10' does not exist in the current context // switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17), // (108,43): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Switch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) switch (TakeOutParam(1, out var x1) ? 1 : 0) { case 0: break; } Dummy(x1, 1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,15): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Switch_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@" switch (Dummy(TakeOutParam(true, out var x1), x1)) {} "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1))) { case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_SwitchLabelGuard_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test1(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 1 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 2 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; } } void Test2(int val) { switch (val) { case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Dummy(x2); break; } } void Test3(int x3, int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x3), x3): Dummy(x3); break; } } void Test4(int val) { var x4 = 11; switch (val) { case 0 when Dummy(TakeOutParam(true, out var x4), x4): Dummy(x4); break; case 1 when Dummy(x4): Dummy(x4); break; } } void Test5(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x5), x5): Dummy(x5); break; } var x5 = 11; Dummy(x5); } //void Test6(int val) //{ // let x6 = 11; // switch (val) // { // case 0 when Dummy(x6): // Dummy(x6); // break; // case 1 when Dummy(TakeOutParam(true, out var x6), x6): // Dummy(x6); // break; // } //} //void Test7(int val) //{ // switch (val) // { // case 0 when Dummy(TakeOutParam(true, out var x7), x7): // Dummy(x7); // break; // } // let x7 = 11; // Dummy(x7); //} void Test8(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test9(int val) { switch (val) { case 0 when Dummy(x9): int x9 = 9; Dummy(x9); break; case 2 when Dummy(x9 = 9): Dummy(x9); break; case 1 when Dummy(TakeOutParam(true, out var x9), x9): Dummy(x9); break; } } //void Test10(int val) //{ // switch (val) // { // case 1 when Dummy(TakeOutParam(true, out var x10), x10): // Dummy(x10); // break; // case 0 when Dummy(x10): // let x10 = 10; // Dummy(x10); // break; // case 2 when Dummy(x10 = 10, x10): // Dummy(x10); // break; // } //} void Test11(int val) { switch (x11 ? val : 0) { case 0 when Dummy(x11): Dummy(x11, 0); break; case 1 when Dummy(TakeOutParam(true, out var x11), x11): Dummy(x11, 1); break; } } void Test12(int val) { switch (x12 ? val : 0) { case 0 when Dummy(TakeOutParam(true, out var x12), x12): Dummy(x12, 0); break; case 1 when Dummy(x12): Dummy(x12, 1); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case 1 when Dummy(TakeOutParam(true, out var x13), x13): Dummy(x13); break; } } void Test14(int val) { switch (val) { case 1 when Dummy(TakeOutParam(true, out var x14), x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test15(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x15), x15): case 1 when Dummy(TakeOutParam(true, out var x15), x15): Dummy(x15); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (30,31): error CS0841: Cannot use local variable 'x2' before it is declared // case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31), // (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x3), x3): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58), // (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x4), x4): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58), // (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x5), x5): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58), // (102,95): error CS0128: A local variable named 'x8' is already defined in this scope // case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95), // (112,31): error CS0841: Cannot use local variable 'x9' before it is declared // case 0 when Dummy(x9): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31), // (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x9), x9): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58), // (144,17): error CS0103: The name 'x11' does not exist in the current context // switch (x11 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17), // (146,31): error CS0103: The name 'x11' does not exist in the current context // case 0 when Dummy(x11): Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31), // (147,23): error CS0103: The name 'x11' does not exist in the current context // Dummy(x11, 0); Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23), // (157,17): error CS0103: The name 'x12' does not exist in the current context // switch (x12 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17), // (162,31): error CS0103: The name 'x12' does not exist in the current context // case 1 when Dummy(x12): Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31), // (163,23): error CS0103: The name 'x12' does not exist in the current context // Dummy(x12, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23), // (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x13), x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58), // (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x14), x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58), // (198,58): error CS0128: A local variable named 'x15' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58), // (198,64): error CS0165: Use of unassigned local variable 'x15' // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(6, x1Ref.Length); for (int i = 0; i < x1Decl.Length; i++) { VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]); } var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(4, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyNotAnOutLocal(model, x4Ref[3]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]); VerifyNotAnOutLocal(model, x5Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(6, x9Ref.Length); VerifyNotAnOutLocal(model, x9Ref[0]); VerifyNotAnOutLocal(model, x9Ref[1]); VerifyNotAnOutLocal(model, x9Ref[2]); VerifyNotAnOutLocal(model, x9Ref[3]); VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(5, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyNotInScope(model, x11Ref[1]); VerifyNotInScope(model, x11Ref[2]); VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(5, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]); VerifyNotInScope(model, x12Ref[3]); VerifyNotInScope(model, x12Ref[4]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]); VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Decl.Length); Assert.Equal(3, x15Ref.Length); for (int i = 0; i < x15Ref.Length; i++) { VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]); } [Fact] public void Scope_SwitchLabelGuard_02() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_03() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): while (TakeOutParam(x1, out var y1) && Print(y1)) break; break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_04() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): do val = 0; while (TakeOutParam(x1, out var y1) && Print(y1)); break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_05() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): lock ((object)TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_06() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): if (TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): switch (TakeOutParam(x1, out var y1)) { default: break; } System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_08() { var source = @" public class X { public static void Main() { foreach (var x in Test(1)) {} } static System.Collections.IEnumerable Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): yield return TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_09() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z1 = x1 > 0 & TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_10() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): a: TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (14,1): warning CS0164: This label has not been referenced // a: TakeOutParam(x1, out var y1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_11() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): return TakeOutParam(x1, out var y1) && Print(y1); System.Console.WriteLine(y1); break; } return false; } static bool Print<T>(T x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (15,17): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_12() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { try { switch (val) { case 1 when TakeOutParam(123, out var x1): throw Dummy(TakeOutParam(x1, out var y1), y1); System.Console.WriteLine(y1); break; } } catch {} return false; } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (17,21): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_13() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_14() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelPattern_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test8(object val) { switch (val) { case int x8 when Dummy(x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case int x13 when Dummy(x13): Dummy(x13); break; } } void Test14(object val) { switch (val) { case int x14 when Dummy(x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test16(object val) { switch (val) { case int x16 when Dummy(x16): case 1 when Dummy(TakeOutParam(true, out var x16), x16): Dummy(x16); break; } } void Test17(object val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x17), x17): case int x17 when Dummy(x17): Dummy(x17); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,64): error CS0128: A local variable named 'x8' is already defined in this scope // when Dummy(x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64), // (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x13 when Dummy(x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22), // (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x14 when Dummy(x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22), // (51,58): error CS0128: A local variable named 'x16' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58), // (51,64): error CS0165: Use of unassigned local variable 'x16' // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64), // (62,22): error CS0128: A local variable named 'x17' is already defined in this scope // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22), // (62,37): error CS0165: Use of unassigned local variable 'x17' // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyNotAnOutLocal(model, x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]); VerifyNotAnOutLocal(model, x13Ref[3]); VerifyNotAnOutLocal(model, x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").Single(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(4, x14Ref.Length); VerifyNotAnOutLocal(model, x14Ref[0]); VerifyNotAnOutLocal(model, x14Ref[1]); VerifyNotAnOutLocal(model, x14Ref[2]); VerifyNotAnOutLocal(model, x14Ref[3]); VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x16Decl = GetOutVarDeclarations(tree, "x16").Single(); var x16Ref = GetReferences(tree, "x16").ToArray(); Assert.Equal(3, x16Ref.Length); for (int i = 0; i < x16Ref.Length; i++) { VerifyNotAnOutLocal(model, x16Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x16Decl); var x17Decl = GetOutVarDeclarations(tree, "x17").Single(); var x17Ref = GetReferences(tree, "x17").ToArray(); Assert.Equal(3, x17Ref.Length); VerifyModelForOutVar(model, x17Decl, x17Ref); } [Fact] public void Scope_ThrowStatement_01() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1() { throw Dummy(TakeOutParam(true, out var x1), x1); { throw Dummy(TakeOutParam(true, out var x1), x1); } throw Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { throw Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { throw Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); throw Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { throw Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // throw Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // throw Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) throw Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) throw Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); throw Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { throw Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52), // (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48), // (21,21): error CS0841: Cannot use local variable 'x2' before it is declared // throw Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21), // (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48), // (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ThrowStatement_02() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1(bool val) { if (val) throw Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ThrowStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@" throw Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(TakeOutParam(""throw"", out var x2), x2); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(TakeOutParam(""throw 1"", out var x2), x2); if (!val) { throw Dummy(TakeOutParam(""throw 2"", out var x2), x2); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Using_01() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49), // (35,22): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53), // (68,35): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35), // (86,35): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (var d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (var d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (var d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72), // (35,45): error CS0841: Cannot use local variable 'x6' before it is declared // using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76), // (68,58): error CS0103: The name 'y10' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58), // (86,58): error CS0103: The name 'y12' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,69): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_04() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,58): error CS0128: A local variable named 'x1' is already defined in this scope // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (12,63): error CS0841: Cannot use local variable 'x1' before it is declared // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63), // (20,73): error CS0128: A local variable named 'x2' is already defined in this scope // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73), // (20,78): error CS0165: Use of unassigned local variable 'x2' // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_Using_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } void Test3() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4)) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void Scope_While_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { while (TakeOutParam(true, out var x1) && x1) { Dummy(x1); } } void Test2() { while (TakeOutParam(true, out var x2) && x2) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); while (TakeOutParam(true, out var x4) && x4) Dummy(x4); } void Test6() { while (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { while (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { while (TakeOutParam(true, out var x8) && x8) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { while (TakeOutParam(true, out var x9) && x9) { Dummy(x9); while (TakeOutParam(true, out var x9) && x9) // 2 Dummy(x9); } } void Test10() { while (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // while (TakeOutParam(y11, out var x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { while (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // while (TakeOutParam(y13, out var x13)) // let y13 = 12; //} void Test14() { while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43), // (35,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47), // (68,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29), // (86,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_While_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) while (TakeOutParam(true, out var x1)) { ; } x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_While_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@" while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) f = false; f = true; if (f) { while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 4"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Yield_01() { var source = @" using System.Collections; public class X { public static void Main() { } object Dummy(params object[] x) { return null;} IEnumerable Test1() { yield return Dummy(TakeOutParam(true, out var x1), x1); { yield return Dummy(TakeOutParam(true, out var x1), x1); } yield return Dummy(TakeOutParam(true, out var x1), x1); } IEnumerable Test2() { yield return Dummy(x2, TakeOutParam(true, out var x2)); } IEnumerable Test3(int x3) { yield return Dummy(TakeOutParam(true, out var x3), x3); } IEnumerable Test4() { var x4 = 11; Dummy(x4); yield return Dummy(TakeOutParam(true, out var x4), x4); } IEnumerable Test5() { yield return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //IEnumerable Test6() //{ // let x6 = 11; // Dummy(x6); // yield return Dummy(TakeOutParam(true, out var x6), x6); //} //IEnumerable Test7() //{ // yield return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} IEnumerable Test8() { yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } IEnumerable Test9(bool y9) { if (y9) yield return Dummy(TakeOutParam(true, out var x9), x9); } IEnumerable Test11() { Dummy(x11); yield return Dummy(TakeOutParam(true, out var x11), x11); } IEnumerable Test12() { yield return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59), // (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55), // (23,28): error CS0841: Cannot use local variable 'x2' before it is declared // yield return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28), // (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55), // (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55), // (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13), // (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13), // (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92), // (72,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_Yield_02() { var source = @" using System.Collections; public class X { public static void Main() { } IEnumerable Test1() { if (true) yield return TakeOutParam(true, out var x1); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Yield_03() { var source = @" using System.Collections; public class X { public static void Main() { } void Dummy(params object[] x) {} IEnumerable Test1() { yield return 0; SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@" yield return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); yield return Dummy(TakeOutParam(""yield2"", out var x2), x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); if (f) { yield return Dummy(TakeOutParam(""yield2"", out var x1), x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_LabeledStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { a: Dummy(TakeOutParam(true, out var x1), x1); { b: Dummy(TakeOutParam(true, out var x1), x1); } c: Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { a: Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { a: Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); a: Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { a: Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); //a: Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ //a: Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) a: Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) a: Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); a: Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { a: Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (12,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1), // (14,1): warning CS0164: This label has not been referenced // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1), // (16,1): warning CS0164: This label has not been referenced // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (21,1): warning CS0164: This label has not been referenced // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (26,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (33,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (38,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x5), x5); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (59,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1), // (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1), // (65,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1), // (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1), // (73,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (80,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x11), x11); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1), // (85,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x12), x12); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_LabeledStatement_02() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) a: Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1), // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9), // (13,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_LabeledStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@" a: b: Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { a: b: c:Test2(Test1(out int x1), x1); System.Console.Write(x1); return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics( // (11,1): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1), // (11,4): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4), // (11,7): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void DataFlow_01() { var text = @" public class Cls { public static void Main() { Test(out int x1, x1); } static void Test(out int x, int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_02() { var text = @" public class Cls { public static void Main() { Test(out int x1, ref x1); } static void Test(out int x, ref int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // ref x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_03() { var text = @" public class Cls { public static void Main() { Test(out int x1); var x2 = 1; } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used // var x2 = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var dataFlow = model.AnalyzeDataFlow(x2Decl); Assert.True(dataFlow.Succeeded); Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString()); Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString()); } [Fact] public void TypeMismatch_01() { var text = @" public class Cls { public static void Main() { Test(out int x1); } static void Test(out short x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short' // Test(out int x1); Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_01() { var text = @" public class Cls { public static void Main() { Test(int x1); Test(ref int x2); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,14): error CS1525: Invalid expression term 'int' // Test(int x1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // Test(int x1); Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18), // (7,18): error CS1525: Invalid expression term 'int' // Test(ref int x2); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // Test(ref int x2); Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22), // (6,18): error CS0103: The name 'x1' does not exist in the current context // Test(int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18), // (7,22): error CS0103: The name 'x2' does not exist in the current context // Test(ref int x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void Parse_02() { var text = @" public class Cls { public static void Main() { Test(out int x1.); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,24): error CS1003: Syntax error, ',' expected // Test(out int x1.); Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_03() { var text = @" public class Cls { public static void Main() { Test(out System.Collections.Generic.IEnumerable<System.Int32>); } static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable // Test(out System.Collections.Generic.IEnumerable<System.Int32>); Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void GetAliasInfo_01() { var text = @" using a = System.Int32; public class Cls { public static void Main() { Test1(out a x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GetAliasInfo_02() { var text = @" using var = System.Int32; public class Cls { public static void Main() { Test1(out var x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void VarIsNotVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out var x) { x = new var() {val = 123}; return null; } static void Test2(object x, var y) { System.Console.WriteLine(y.val); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void VarIsNotVar_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test1' does not exist in the current context // Test1(out var x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9), // (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0 // public int val; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void SimpleVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static void Test2(object x, object y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0103: The name 'Test1' does not exist in the current context // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_03() { var text = @" public class Cls { public static void Main() { Test1(out var x1, out x1); } static object Test1(out int x, out int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // out x1); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_04() { var text = @" public class Cls { public static void Main() { Test1(out var x1, Test1(out x1, 3)); } static object Test1(out int x, int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // Test1(out x1, Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(ref int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_07() { var text = @" public class Cls { public static void Main() { dynamic x = null; Test2(x.Test1(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x.Test1(out var x1), Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_08() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var x1), x1); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_09() { var text = @" public class Cls { public static void Main() { Test2(new System.Action(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,37): error CS0149: Method name expected // Test2(new System.Action(out var x1), Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void ConstructorInitializers_01() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x, object y) { System.Console.WriteLine(y); } public Test2() : this(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : this(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26) ); var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); var typeInfo = model.GetTypeInfo(initializer); var symbolInfo = model.GetSymbolInfo(initializer); var group = model.GetMemberGroup(initializer); Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936 } [Fact] public void ConstructorInitializers_02() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { public Test2(object x, object y) { System.Console.WriteLine(y); } } class Test3 : Test2 { public Test3() : base(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : base(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26) ); } [Fact] public void ConstructorInitializers_03() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} class Test2 { Test2(out int x) { x = 2; } public Test2() : this(out var x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void ConstructorInitializers_04() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} class Test2 { public Test2(out int x) { x = 1; } } class Test3 : Test2 { public Test3() : base(out var x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_05() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(System.Func<object> x) { System.Console.WriteLine(x()); } public Test2() : this(() => { Test1(out var x1); return x1; }) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_06() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_07() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_08() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (23,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(23, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer(); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular) .GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.True(analyzer.ActionFired); } private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer { public bool ActionFired { get; private set; } private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer); } private void Handle(SyntaxNodeAnalysisContext context) { ActionFired = true; var tree = context.Node.SyntaxTree; var model = context.SemanticModel; var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent; SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl)); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0])); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1])); } } [Fact] public void ConstructorInitializers_09() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_10() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_11() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (21,37): error CS0165: Use of unassigned local variable 'x1' // => System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_12() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_13() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_14() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_15() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_16() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_17() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_14() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_15() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var var), var); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var varDecl = GetOutVarDeclaration(tree, "var"); var varRef = GetReferences(tree, "var").Skip(1).Single(); VerifyModelForOutVar(model, varDecl, varRef); } [Fact] public void SimpleVar_16() { var text = @" public class Cls { public static void Main() { if (Test1(out var x1)) { System.Console.WriteLine(x1); } } static bool Test1(out int x) { x = 123; return true; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void VarAndBetterness_01() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); Test2(out var x2, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, string y) { x = 124; System.Console.WriteLine(x); return null; } static object Test2(out int x, string y) { x = 125; System.Console.WriteLine(x); return null; } static object Test2(out short x, object y) { x = 126; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); VerifyModelForOutVar(model, x2Decl); } [Fact] public void VarAndBetterness_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, object y) { x = 124; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)' // Test1(out var x1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.ArgIterator x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_03() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25), // (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void RestrictedTypes_04() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out System.ArgIterator x1), x1); var x = default(System.ArgIterator); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out System.ArgIterator x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25), // (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // var x = default(System.ArgIterator); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9), // (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ElementAccess_01() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out var x1]); Test2(x1); Test2(x[out var _]); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25), // (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21), // (9,21): error CS8183: Cannot infer the type of implicitly-typed discard. // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21) ); } [Fact] public void PointerAccess_01() { var text = @" public class Cls { public static unsafe void Main() { int* p = (int*)0; Test2(p[out var x1]); Test2(x1); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25) ); } [Fact] public void ElementAccess_02() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out int x1], x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21), // (7,21): error CS0165: Use of unassigned local variable 'x1' // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21) ); } [Fact] [WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")] public void MissingArgumentAndNamedOutVarArgument() { var source = @"class Program { public static void Main(string[] args) { if (M(s: out var s)) { string s2 = s; } } public static bool M(int i, out string s) { s = i.ToString(); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)' // if (M(s: out var s)) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13) ); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_01() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x); System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_02() { var text = @" public class Cls { public static void Main() { var y = Test1(out int x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_03() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_04() { var text = @" public class Cls { public static void Main() { for (var y = Test1(out var x) + x; y != 0 ; y = 0) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_05() { var text = @" public class Cls { public static void Main() { foreach (var y in new [] {Test1(out var x) + x}) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_06() { var text = @" public class Cls { public static void Main() { Test1(x: 1, out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21), // (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_07() { var text = @" public class Cls { public static void Main() { int x = 0; Test1(y: ref x, y: out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)' // Test1(y: ref x, y: out var y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); var yRef = GetReferences(tree, "y").ToArray(); Assert.Equal(3, yRef.Length); Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString()); VerifyModelForOutVar(model, yDecl, yRef[2]); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamic() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int z]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @"{ // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) //z IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret }"); } [Fact] public void IndexingDynamicWithDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @" { // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret } "); } [Fact] public void IndexingDynamicWithVarDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out var _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23) ); } [Fact] public void IndexingDynamicWithShortDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out _]; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutVar() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.True(x1.Type.IsErrorType()); VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var x = d[out var x1] + x1; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutInt() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void OutVariableDeclarationInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; return 2; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.2 ret } // i = 3; return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.3 stind.i4 ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 4; return 5; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.5 ret } // i = 6; return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.6 stind.i4 ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} x1] + "" "" + x1); ia.P[out {0} x2] = 4; Console.WriteLine(x2); Console.WriteLine(ia[out {0} x3] + "" "" + x3); ia[out {0} x4] = 4; Console.WriteLine(x4); }} }}"; string[] fillIns = new[] { "int", "var" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString()); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString()); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(1, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString()); CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"2 1 3 5 4 6") .VerifyIL("B.Main()", @"{ // Code size 113 (0x71) .maxstack 4 .locals init (int V_0, //x1 int V_1, //x2 int V_2, //x3 int V_3, //x4 int V_4) IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: callvirt ""int IA.P[out int].get"" IL_000d: stloc.s V_4 IL_000f: ldloca.s V_4 IL_0011: call ""string int.ToString()"" IL_0016: ldstr "" "" IL_001b: ldloca.s V_0 IL_001d: call ""string int.ToString()"" IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: dup IL_002d: ldloca.s V_1 IL_002f: ldc.i4.4 IL_0030: callvirt ""void IA.P[out int].set"" IL_0035: ldloc.1 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: dup IL_003c: ldloca.s V_2 IL_003e: callvirt ""int IA.this[out int].get"" IL_0043: stloc.s V_4 IL_0045: ldloca.s V_4 IL_0047: call ""string int.ToString()"" IL_004c: ldstr "" "" IL_0051: ldloca.s V_2 IL_0053: call ""string int.ToString()"" IL_0058: call ""string string.Concat(string, string, string)"" IL_005d: call ""void System.Console.WriteLine(string)"" IL_0062: ldloca.s V_3 IL_0064: ldc.i4.4 IL_0065: callvirt ""void IA.this[out int].set"" IL_006a: ldloc.3 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret }"); } } [ClrOnlyFact] public void OutVariableDiscardInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; System.Console.WriteLine(11); return 111; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x06F ret } // i = 2; System.Console.Write(22); return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.2 stind.i4 ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 3; System.Console.WriteLine(33) return 333; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.3 stind.i4 ldc.i4.s 33 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x14D ret } // i = 4; System.Console.WriteLine(44); return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.s 44 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} _]); ia.P[out {0} _] = 4; Console.WriteLine(ia[out {0} _]); ia[out {0} _] = 4; }} }}"; string[] fillIns = new[] { "int", "var", "" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"11 111 22 33 333 44") .VerifyIL("B.Main()", @" { // Code size 58 (0x3a) .maxstack 3 .locals init (A V_0, //a IA V_1, //ia int V_2) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloca.s V_2 IL_000c: callvirt ""int IA.P[out int].get"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ldloc.1 IL_0018: ldloca.s V_2 IL_001a: ldc.i4.4 IL_001b: callvirt ""void IA.P[out int].set"" IL_0020: nop IL_0021: ldloc.1 IL_0022: ldloca.s V_2 IL_0024: callvirt ""int IA.this[out int].get"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ldloc.1 IL_0030: ldloca.s V_2 IL_0032: ldc.i4.4 IL_0033: callvirt ""void IA.this[out int].set"" IL_0038: nop IL_0039: ret }"); } } [Fact] public void ElementAccess_04() { var text = @" using System.Collections.Generic; public class Cls { public static void Main() { var list = new Dictionary<int, long> { [out var x1] = 3, [out var _] = 4, [out _] = 5 }; System.Console.Write(x1); System.Console.Write(_); { int _ = 1; var list2 = new Dictionary<int, long> { [out _] = 6 }; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var x1] = 3, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18), // (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var _] = 4, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18), // (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out _] = 5 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18), // (14,30): error CS0103: The name '_' does not exist in the current context // System.Console.Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30), // (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword // var list2 = new Dictionary<int, long> { [out _] = 6 }; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58) ); } [Fact] public void ElementAccess_05() { var text = @" public class Cls { public static void Main() { int[out var x1] a = null; // fatal syntax error - 'out' is skipped int b(out var x2) = null; // parsed as a local function with syntax error int c[out var x3] = null; // fatal syntax error - 'out' is skipped int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator x4 = 0; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count()); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); compilation.VerifyDiagnostics( // (6,13): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13), // (6,21): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21), // (7,27): error CS1002: ; expected // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27), // (7,27): error CS1525: Invalid expression term '=' // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27), // (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14), // (8,15): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15), // (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19), // (8,23): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23), // (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23), // (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17), // (10,17): error CS1003: Syntax error, '[' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17), // (10,28): error CS1003: Syntax error, ']' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28), // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12), // (6,17): error CS0103: The name 'var' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17), // (6,21): error CS0103: The name 'x1' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21), // (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body. // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13), // (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19), // (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29), // (8,19): error CS0103: The name 'var' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19), // (8,23): error CS0103: The name 'x3' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23), // (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13), // (6,25): warning CS0219: The variable 'a' is assigned but its value is never used // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25), // (10,13): warning CS0168: The variable 'd' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13), // (10,16): warning CS0168: The variable 'e' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16), // (7,13): warning CS8321: The local function 'b' is declared but never used // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13) ); } [Fact] public void ElementAccess_06() { var text = @" public class Cls { public static void Main() { { int[] e = null; var z1 = e?[out var x1]; x1 = 1; } { int[][] e = null; var z2 = e?[out var x2]?[out var x3]; x2 = 1; x3 = 2; } { int[][] e = null; var z3 = e?[0]?[out var x4]; x4 = 1; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var x2Decl = GetOutVarDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29), // (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33), // (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29), // (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'. // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33), // (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33), // (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'. // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37) ); } [Fact] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[out var x1, x1]; //fixed int F2[3 is int x2 ? x2 : 3]; //fixed int F2[3 is int x3 ? 3 : 3, x3]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Empty(GetOutVarDeclarations(tree, "x1")); compilation.VerifyDiagnostics( // (4,18): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18), // (4,26): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26), // (4,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17), // (4,22): error CS0103: The name 'var' does not exist in the current context // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22) ); } [Fact] public void Scope_DeclaratorArguments_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { int d,e(Dummy(TakeOutParam(true, out var x1), x1)); } void Test4() { var x4 = 11; Dummy(x4); int d,e(Dummy(TakeOutParam(true, out var x4), x4)); } void Test6() { int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); } void Test8() { int d,e(Dummy(TakeOutParam(true, out var x8), x8)); System.Console.WriteLine(x8); } void Test14() { int d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // int d,e(Dummy(TakeOutParam(true, out var x4), x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (30,34): error CS0165: Use of unassigned local variable 'x8' // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl) { Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl)); } private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls) { foreach (var decl in decls) { AssertContainedInDeclaratorArguments(decl); } } [Fact] public void Scope_DeclaratorArguments_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d, x1( Dummy(TakeOutParam(true, out var x1), x1)); Dummy(x1); } void Test2() { object d, x2( Dummy(TakeOutParam(true, out var x2), x2)); Dummy(x2); } void Test3() { object x3, d( Dummy(TakeOutParam(true, out var x3), x3)); Dummy(x3); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,13): error CS0818: Implicitly-typed variables must be initialized // var d, x1( Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13), // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (21,15): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15), // (27,54): error CS0128: A local variable named 'x3' is already defined in this scope // Dummy(TakeOutParam(true, out var x3), x3)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54), // (28,15): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1( Dummy(x1)); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2(Dummy(x3)); } void Test4() { object d1,e(Dummy(x4)], d2(Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1( Dummy(x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (14,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1,e(Dummy(x4)], Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 (Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (13,27): error CS0165: Use of unassigned local variable 'x1' // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59), // (26,27): error CS0165: Use of unassigned local variable 'x3' // d2 = Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y, y1(Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single(); Assert.Equal("var y1", y1.ToTestDisplayString()); Assert.True(((ILocalSymbol)y1).Type.IsErrorType()); } [Fact] public void Scope_DeclaratorArguments_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d,e(TakeOutParam(true, out var x1) && x1 != null); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13), // (11,17): error CS0818: Implicitly-typed variables must be initialized // var d,e(TakeOutParam(true, out var x1) && x1 != null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e); Assert.Equal("var e", symbol.ToTestDisplayString()); Assert.True(symbol.Type.IsErrorType()); } [Fact] [WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")] public void Scope_DeclaratorArguments_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)]; System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); AssertContainedInDeclaratorArguments(y1Decl); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType()); } [Fact] [WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")] public void Scope_DeclaratorArguments_08() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool a, b( Dummy(TakeOutParam(true, out var x1) && x1) );;) { Dummy(x1); } } void Test2() { for (bool a, b( Dummy(TakeOutParam(true, out var x2) && x2) );;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool a, b( Dummy(TakeOutParam(true, out var x4) && x4) );;) Dummy(x4); } void Test6() { for (bool a, b( Dummy(x6 && TakeOutParam(true, out var x6)) );;) Dummy(x6); } void Test7() { for (bool a, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool a, b( Dummy(TakeOutParam(true, out var x8) && x8) );;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool a1, b1( Dummy(TakeOutParam(true, out var x9) && x9) );;) { Dummy(x9); for (bool a2, b2( Dummy(TakeOutParam(true, out var x9) && x9) // 2 );;) Dummy(x9); } } void Test10() { for (bool a, b( Dummy(TakeOutParam(y10, out var x10)) );;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool a, b( // Dummy(TakeOutParam(y11, out var x11)) // );;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool a, b( Dummy(TakeOutParam(y12, out var x12)) );;) var y12 = 12; } //void Test13() //{ // for (bool a, b( // Dummy(TakeOutParam(y13, out var x13)) // );;) // let y13 = 12; //} void Test14() { for (bool a, b( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) );;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_09() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { for (bool d, x4( Dummy(TakeOutParam(true, out var x4) && x4) );;) {} } void Test7() { for (bool x7 = true, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) {} } void Test8() { for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)], b2(Dummy(TakeOutParam(true, out var x8) && x8)); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2(Dummy(TakeOutParam(true, out var x9) && x9)); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47), // (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47), // (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used // for (bool x7 = true, b( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19), // (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2(Dummy(TakeOutParam(true, out var x8) && x8)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52), // (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47), // (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47), // (37,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23), // (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47), // (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl[0]); AssertContainedInDeclaratorArguments(x8Decl[1]); VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]); } [Fact] public void Scope_DeclaratorArguments_10() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,e(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (var d,e(Dummy(TakeOutParam(true, out var x2), x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Dummy(x4); } void Test6() { using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d,e(Dummy(TakeOutParam(true, out var x8), x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d,a(Dummy(TakeOutParam(true, out var x9), x9))) { Dummy(x9); using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Dummy(x9); } } void Test10() { using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) var y12 = 12; } //void Test13() //{ // using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13))) // let y13 = 12; //} void Test14() { using (var d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); AssertContainedInDeclaratorArguments(x10Decl); VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_11() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope // using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope // using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); AssertContainedInDeclaratorArguments(x2Decl); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_DeclaratorArguments_12() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } void Test3() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2(Dummy(TakeOutParam(true, out var x4), x4))) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_13() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Dummy(x4); } void Test6() { fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9))) { Dummy(x9); fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Dummy(x9); } } void Test10() { fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11)))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) var y12 = 12; } //void Test13() //{ // fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13)))) // let y13 = 12; //} void Test14() { fixed (int* p,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_14() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* d,x1( Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)], x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p(Dummy(TakeOutParam(true, out var x3) && x3))) { Dummy(x3); } } void Test4() { fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)], p2(Dummy(TakeOutParam(true, out var x4) && x4))) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Scope_DeclaratorArguments_15() { var source = @" public class X { public static void Main() { } bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; bool Test4 [x4 && TakeOutParam(4, out var x4)]; bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } private static void VerifyModelNotSupported( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax)); Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var identifierText = decl.Identifier().ValueText; Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any()); Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText)); Assert.Null(model.GetSymbolInfo(decl.Type).Symbol); AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null); VerifyModelNotSupported(model, references); } private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references) { foreach (var reference in references) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart)); Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType()); } } [Fact] public void Scope_DeclaratorArguments_16() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; fixed bool Test4 [x4 && TakeOutParam(4, out var x4)]; fixed bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; fixed bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; fixed bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; fixed bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField, (int)ErrorCode.ERR_NoImplicitConv }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 [x4 && TakeOutParam(4, out var x4)]; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (20,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 [Dummy(x7, 2)]; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25), // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_17() { var source = @" public class X { public static void Main() { } const bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; const bool Test4 [x4 && TakeOutParam(4, out var x4)]; const bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; const bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; const bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; const bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_18() { var source = @" public class X { public static void Main() { } event bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; event bool Test4 [x4 && TakeOutParam(4, out var x4)]; event bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; event bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; event bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; event bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.ERR_EventNotDelegate, (int)ErrorCode.WRN_UnreferencedEvent }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_19() { var source = @" public unsafe struct X { public static void Main() { } fixed bool d[2], Test3 (out var x3); } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (8,28): error CS1003: Syntax error, '[' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28), // (8,39): error CS1003: Syntax error, ']' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39), // (8,33): error CS8185: A declaration is not allowed in this context. // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_20() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3[out var x3]; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,22): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22), // (8,30): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30), // (8,21): error CS7092: A fixed buffer may only have one dimension. // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21), // (8,26): error CS0103: The name 'var' does not exist in the current context // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); } [Fact] public void StaticType() { var text = @" public class Cls { public static void Main() { Test1(out StaticType x1); } static object Test1(out StaticType x) { throw new System.NotSupportedException(); } static class StaticType {} }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters // static object Test1(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19), // (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType' // Test1(out StaticType x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19) ); } [Fact] public void GlobalCode_Catch_01() { var source = @" bool Dummy(params object[] x) {return true;} try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34), // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42), // (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13), // (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Catch_02() { var source = @" try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Block_01() { string source = @" { H.TakeOutParam(1, out var x1); H.Dummy(x1); } object x2; { H.TakeOutParam(2, out var x2); H.Dummy(x2); } { H.TakeOutParam(3, out var x3); } H.Dummy(x3); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,8): warning CS0168: The variable 'x2' is declared but never used // object x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8), // (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31), // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } } [Fact] public void GlobalCode_Block_02() { string source = @" { H.TakeOutParam(1, out var x1); System.Console.WriteLine(x1); Test(); void Test() { System.Console.WriteLine(x1); } } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_For_01() { var source = @" bool Dummy(params object[] x) {return true;} for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } for ( // 2 Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42), // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_For_02() { var source = @" bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_Foreach_01() { var source = @"using static Helpers; System.Collections.IEnumerable Dummy(params object[] x) {return null;} foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } static class Helpers { public static bool TakeOutParam(int y, out int x) { x = y; return true; } public static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Foreach_02() { var source = @" bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_01() { var source = @" bool Dummy(params object[] x) {return true;} Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0)); Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) && TakeOutParam(o2, out var x5) && x5 > 0)); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0)); Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0), x7); Dummy(x7, 2); Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out var x9) && x9 > 0), x9); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) && x10 > 0), TakeOutParam(true, out var x10), x10); var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) && x11 > 0), x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutField(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutField(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutField(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7), // (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7), // (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79), // (37,9): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9), // (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13), // (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void GlobalCode_Lambda_02() { var source = @" System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); System.Console.WriteLine(l()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_03() { var source = @" System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Query_01() { var source = @" using System.Linq; bool Dummy(params object[] x) {return true;} var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutField(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutField(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutField(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutField(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutField(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutField(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutField(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutField(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutField(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutField(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutField(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutField(model, y10Decl, y10Ref[0]); VerifyNotAnOutField(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutField(model, y11Decl, y11Ref[0]); VerifyNotAnOutField(model, y11Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7), // (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18), // (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } } [Fact] public void GlobalCode_Query_02() { var source = @" using System.Linq; var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutField(model, yDecl, yRef); } [Fact] public void GlobalCode_Using_01() { var source = @" System.IDisposable Dummy(params object[] x) {return null;} using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_Using_02() { var source = @" using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void GlobalCode_ExpressionStatement_01() { string source = @" H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out int x2); H.TakeOutParam(3, out int x3); object x3; H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } private static void AssertNoGlobalStatements(SyntaxTree tree) { Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()); } [Fact] public void GlobalCode_ExpressionStatement_02() { string source = @" H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out var x2); H.TakeOutParam(3, out var x3); object x3; H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ExpressionStatement_03() { string source = @" System.Console.WriteLine(x1); H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_IfStatement_01() { string source = @" if (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out int x2)) {} if (H.TakeOutParam(3, out int x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} if (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); int x6 = 6; if (H.Dummy()) { string x6 = ""6""; H.Dummy(x6); } void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (30,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17), // (30,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21), // (30,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used // int x6 = 6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5), // (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x6 = "6"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12), // (33,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_IfStatement_02() { string source = @" if (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out var x2)) {} if (H.TakeOutParam(3, out var x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} void Test() { H.Dummy(x1, x2, x3, x4, x5); } if (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,29): error CS0841: Cannot use local variable 'x5' before it is declared // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29), // (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } } [Fact] public void GlobalCode_IfStatement_03() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_IfStatement_04() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_YieldReturnStatement_01() { string source = @" yield return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out int x2); yield return H.TakeOutParam(3, out int x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_YieldReturnStatement_02() { string source = @" yield return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out var x2); yield return H.TakeOutParam(3, out var x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_01() { string source = @" return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out int x2); return H.TakeOutParam(3, out int x3); object x3; return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_02() { string source = @" return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out var x2); return H.TakeOutParam(3, out var x3); object x3; return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_03() { string source = @" System.Console.WriteLine(x1); Test(); return H.Dummy(H.TakeOutParam(1, out var x1), x1); void Test() { System.Console.WriteLine(x1); } class H { public static bool Dummy(object x, object y) { System.Console.WriteLine(y); return true; } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_ThrowStatement_01() { string source = @" throw H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out int x2); throw H.TakeOutParam(3, out int x3); object x3; throw H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ThrowStatement_02() { string source = @" throw H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out var x2); throw H.TakeOutParam(3, out var x3); object x3; throw H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_SwitchStatement_01() { string source = @" switch (H.TakeOutParam(1, out int x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out int x2)) {default: break;} switch (H.TakeOutParam(3, out int x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {default: break;} switch (H.TakeOutParam(51, out int x5)) { default: H.TakeOutParam(""52"", out string x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_02() { string source = @" switch (H.TakeOutParam(1, out var x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out var x2)) {default: break;} switch (H.TakeOutParam(3, out var x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {default: break;} switch (H.TakeOutParam(51, out var x5)) { default: H.TakeOutParam(""52"", out var x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_03() { string source = @" System.Console.WriteLine(x1); switch (H.TakeOutParam(1, out var x1)) { default: H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); break; } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_WhileStatement_01() { string source = @" while (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out int x2)) {} while (H.TakeOutParam(3, out int x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} while (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out int x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_02() { string source = @" while (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out var x2)) {} while (H.TakeOutParam(3, out var x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} while (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out var x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_03() { string source = @" while (H.TakeOutParam(1, out var x1)) { System.Console.WriteLine(x1); break; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_DoStatement_01() { string source = @" do {} while (H.TakeOutParam(1, out int x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out int x2)); do {} while (H.TakeOutParam(3, out int x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))); do { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } while (H.TakeOutParam(51, out int x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out int x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out int x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_02() { string source = @" do {} while (H.TakeOutParam(1, out var x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out var x2)); do {} while (H.TakeOutParam(3, out var x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))); do { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } while (H.TakeOutParam(51, out var x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out var x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out var x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_03() { string source = @" int f = 1; do { } while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3); int Test(int x) { System.Console.WriteLine(x); return x; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2 3").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_LockStatement_01() { string source = @" lock (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out int x2)) {} lock (H.TakeOutParam(3, out int x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} lock (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_02() { string source = @" lock (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out var x2)) {} lock (H.TakeOutParam(3, out var x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} lock (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_03() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_LockStatement_04() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_DeconstructionDeclarationStatement_01() { string source = @" (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); Test(); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (16,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref[0]); } } [Fact] public void GlobalCode_LabeledStatement_01() { string source = @" a: H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out int x2); c: H.TakeOutParam(3, out int x3); object x3; d: H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_02() { string source = @" a: H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out var x2); c: H.TakeOutParam(3, out var x3); object x3; d: H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_03() { string source = @" System.Console.WriteLine(x1); a:b:c:H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_04() { string source = @" a: bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out int x2); e: bool f = H.TakeOutParam(3, out int x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); i: bool x5 = H.TakeOutParam(5, out int x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [Fact] public void GlobalCode_LabeledStatement_05() { string source = @" a: bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out var x2); e: bool f = H.TakeOutParam(3, out var x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); i: bool x5 = H.TakeOutParam(5, out var x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void GlobalCode_LabeledStatement_06_Script() { string source = @" System.Console.WriteLine(x1); a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_06_SimpleProgram() { string source = @" a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_07() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_08() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out var x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out var x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), H.TakeOutParam(6, out var x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_09() { string source = @" System.Console.WriteLine(x1); a:b:c: var (d, e) = (H.TakeOutParam(1, out var x1), 1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_01() { string source = @" bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out int x2); bool f = H.TakeOutParam(3, out int x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 = H.TakeOutParam(5, out int x5); bool i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_02() { string source = @" bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out var x2); bool f = H.TakeOutParam(3, out var x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 = H.TakeOutParam(5, out var x5); bool i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_03() { string source = @" System.Console.WriteLine(x1); var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static var b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_05() { string source = @" bool b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_06() { string source = @" bool b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_07() { string source = @" Test(); bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); bool Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return false; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_PropertyDeclaration_01() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out int x2); bool f { get; } = H.TakeOutParam(3, out int x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 { get; } = H.TakeOutParam(5, out int x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_02() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out var x2); bool f { get; } = H.TakeOutParam(3, out var x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 { get; } = H.TakeOutParam(5, out var x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_03() { string source = @" System.Console.WriteLine(x1); bool d { get; set; } = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static bool b { get; } = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_05() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_06() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_01() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out int x2); event System.Action f = H.TakeOutParam(3, out int x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); event System.Action x5 = H.TakeOutParam(5, out int x5); event System.Action i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_02() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out var x2); event System.Action f = H.TakeOutParam(3, out var x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); event System.Action x5 = H.TakeOutParam(5, out var x5); event System.Action i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_03() { string source = @" System.Console.WriteLine(x1); event System.Action d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static event System.Action b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_05() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_06() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_07() { string source = @" Test(); event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); System.Action Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_DeclaratorArguments_01() { string source = @" bool a, b(out var x1); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_02() { string source = @" label: bool a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1), // (4,9): error CS0165: Use of unassigned local variable 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_03() { string source = @" event System.Action a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static System.Action Dummy(params object[] x) {return null;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_DeclaratorArguments_04() { string source = @" fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static int TakeOutParam<T>(T y, out T x) { x = y; return 3; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to 'b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12), // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_RestrictedType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out System.ArgIterator x2); class H { public static void TakeOutParam(out System.ArgIterator x) { x = default(System.ArgIterator); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public static void TakeOutParam(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37), // (5,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out System.ArgIterator x2); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20), // (3,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_StaticType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out StaticType x2); class H { public static void TakeOutParam(out StaticType x) { x = default(System.ArgIterator); } } static class StaticType{} "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (5,31): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out StaticType x2); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31), // (9,24): error CS0721: 'StaticType': static types cannot be used as parameters // public static void TakeOutParam(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24), // (3,24): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_InferenceFailure_01() { string source = @" H.TakeOutParam(out var x1, x1); class H { public static void TakeOutParam(out int x, long y) { x = 1; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.TakeOutParam(out var x1, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact] public void GlobalCode_InferenceFailure_02() { string source = @" var a = b; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_03() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = a; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = a; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_04() { string source = @" var a = x1; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single()); Assert.True(a.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32) ); } [Fact] public void GlobalCode_InferenceFailure_05() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = x1; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = H.TakeOutParam(out var x1, b); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single(); var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl); Assert.True(b.Type.IsErrorType()); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); Assert.False(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); } [Fact] public void GlobalCode_InferenceFailure_06() { string source = @" H.TakeOutParam(out var x1); class H { public static int TakeOutParam<T>(out T x) { x = default(T); return 123; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24), // (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3) ); compilation.GetDeclarationDiagnostics().Verify( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")] public void GlobalCode_InferenceFailure_07() { string source = @" H.M((var x1, int x2)); H.M(x1); class H { public static void M(object a) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10), // (2,6): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6), // (2,14): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14), // (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5), // (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object' // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5) ); compilation.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")] public void InferenceFailure_01() { string source = @" class H { object M1() => M(M(1), x1); static object M(object o1) => o1; static void M(object o1, object o2) {} } "; var node0 = SyntaxFactory.ParseCompilationUnit(source); var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var decl = SyntaxFactory.DeclarationExpression( type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")), designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1"))); var node1 = node0.ReplaceNode(one, decl); var tree = node1.SyntaxTree; Assert.NotNull(tree); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics( // (4,24): error CS8185: A declaration is not allowed in this context. // object M1() => M(M(varx1), x1); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24) ); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_AliasInfo_01() { string source = @" H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void GlobalCode_AliasInfo_02() { string source = @" using var = System.Int32; H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_03() { string source = @" using a = System.Int32; H.TakeOutParam(1, out a x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_04() { string source = @" H.TakeOutParam(1, out int x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_1() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out var x1): System.Console.WriteLine(x1); break; } } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case !TakeOutParam(3, out var x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_2() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out UndeclaredType x1): System.Console.WriteLine(x1); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19), // (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?) // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, false, references); } private static void VerifyModelForOutFieldDuplicate( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, true, references); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, bool duplicate, params IdentifierNameSyntax[] references) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(SymbolKind.Field, symbol.Kind); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText); var names = model.LookupNames(decl.SpanStart); if (duplicate) { Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, symbols.Single()); } Assert.Contains(decl.Identifier().ValueText, names); var local = (IFieldSymbol)symbol; var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement && (declarator.ArgumentList?.Contains(decl)).GetValueOrDefault(); // We're not able to get type information at such location (out var argument in global code) at this point // See https://github.com/dotnet/roslyn/issues/13569 AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type); foreach (var reference in references) { var referenceInfo = model.GetSymbolInfo(reference); symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText); if (duplicate) { Assert.Null(referenceInfo.Symbol); Assert.Contains(symbol, referenceInfo.CandidateSymbols); Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, referenceInfo.Symbol); Assert.Same(symbol, symbols.Single()); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); } if (!inFieldDeclaratorArgumentlist) { var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent; if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); } else { var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (dataFlow.Succeeded) { Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } } [Fact] public void MethodTypeArgumentInference_01() { var source = @" public class X { public static void Main() { TakeOutParam(out int a); TakeOutParam(out long b); } static void TakeOutParam<T>(out T x) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int64"); } [Fact] public void MethodTypeArgumentInference_02() { var source = @" public class X { public static void Main() { TakeOutParam(out var a); } static void TakeOutParam<T>(out T x) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out var a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9) ); } [Fact] public void MethodTypeArgumentInference_03() { var source = @" public class X { public static void Main() { long a = 0; TakeOutParam(out int b, a); int c; TakeOutParam(out c, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out int b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9), // (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out c, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9) ); } [Fact] public void MethodTypeArgumentInference_04() { var source = @" public class X { public static void Main() { byte a = 0; int b = 0; TakeOutParam(out int c, a); TakeOutParam(out b, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int32"); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void OutVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); } [Fact] public void OutVarDiscard() { var source = @" public class C { static void Main() { M(out int _); M(out var _); M(out _); } static void M(out int x) { x = 1; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.Single(); var model = comp.Compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetTypeInfo(discard2).Type); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); comp.VerifyIL("C.Main()", @" { // Code size 22 (0x16) .maxstack 1 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: call ""void C.M(out int)"" IL_0007: ldloca.s V_0 IL_0009: call ""void C.M(out int)"" IL_000e: ldloca.s V_0 IL_0010: call ""void C.M(out int)"" IL_0015: ret } "); } [Fact] public void NamedOutVarDiscard() { var source = @" public class C { static void Main() { M(y: out string _, x: out int _); M(y: out var _, x: out var _); M(y: out _, x: out _); } static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); } [Fact] public void OutVarDiscardInCtor_01() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out int i1); new C(out int _); new C(out var _); new C(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("int", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact] public void OutVarDiscardInCtor_02() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out long x1); new C(out long _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long x1); Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19), // (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long _); Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19), // (7,19): error CS0165: Use of unassigned local variable 'x1' // new C(out long x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl); var discard1 = GetDiscardDesignations(tree).Single(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("long _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("long", declaration1.Type.ToString()); Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); } [Fact] public void OutVarDiscardAliasInfo_01() { var source = @" using alias1 = System.Int32; using var = System.Int32; public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString()); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString()); } [Fact] public void OutVarDiscardAliasInfo_02() { var source = @" enum alias1 : long {} class var {} public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int' // new C(out alias1 _); Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19), // (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int' // new C(out var _); Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString()); Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("var", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); } [Fact] public void OutVarDiscardInCtorInitializer() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C ""); } static void Main() { new Derived2(out int i2); new Derived3(out int i3); new Derived4(); } } public class Derived2 : C { public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); } } public class Derived3 : C { public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); } } public class Derived4 : C { public Derived4(out int i) : base(out _) { i = 4; } public Derived4() : this(out _) { System.Console.Write(""Derived4""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4"); } [Fact] public void DiscardNotRecognizedInOtherScenarios() { var source = @" public class C { void M<T>() { _.ToString(); M(_); _<T>.ToString(); (_<T>, _<T>) = (1, 2); M<_>(); new C() { _ = 1 }; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): error CS0103: The name '_' does not exist in the current context // _.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9), // (7,11): error CS0103: The name '_' does not exist in the current context // M(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11), // (8,9): error CS0103: The name '_' does not exist in the current context // _<T>.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9), // (9,10): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10), // (9,16): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16), // (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // M<_>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11), // (11,19): error CS0117: 'C' does not contain a definition for '_' // new C() { _ = 1 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19) ); } [Fact] public void TypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); System.Console.Write(t.GetType().ToString()); } static void Main() { M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "System.Int32"); } [Fact] public void UntypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); } static void Main() { M(out var _); M(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out var _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9), // (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9) ); } [Fact] public void PickOverloadWithTypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); } static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); } static void Main() { M(out object _); M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "object returning M. int returning M."); } [Fact] public void CannotPickOverloadWithUntypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; } static void M(out int x) { x = 2; } static void Main() { M(out var _); M(out _); M(out byte _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out var _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9), // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9), // (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object' // M(out byte _); Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15) ); } [Fact] public void NoOverloadWithDiscard() { var source = @" public class A { } public class B : A { static void M(A a) { a.M2(out A x); a.M2(out A _); } } public static class S { public static void M2(this A self, out B x) { x = null; } }"; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore }); comp.VerifyDiagnostics( // (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A x); Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18), // (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A _); Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18) ); } [Fact] [WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")] public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier() { var source = @" public class C { static void M(string x) { if(true) && int.TryParse(x, out int y)) id(iVal); // Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single(); Assert.Equal("x", x.ToString()); Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString()); } [Fact] public void DuplicateDeclarationInSwitchBlock() { var text = @" public class C { public static void Main(string[] args) { switch (args.Length) { case 0: M(M(out var x1), x1); M(M(out int x1), x1); break; case 1: M(M(out int x1), x1); break; } } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics( // (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29), // (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29), // (13,34): error CS0165: Use of unassigned local variable 'x1' // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x6Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x6Decl.Length); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]); } [Fact] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(int a, int b) => a+b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,75): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,75): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInAnonymousMethodParameterDefault() { var text = @" class C { public static void Main(int arg) { System.Action<bool, int> d1 = delegate ( bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }; System.Action<bool, int> d2 = delegate ( bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }; int x = z1 + z2; d1 = d2 = null; } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; } "; // the scope of an expression variable introduced in the default expression // of a lambda parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify( // (9,55): error CS0103: The name 'z1' does not exist in the current context // { var t = z1; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55), // (13,55): error CS0103: The name 'z2' does not exist in the current context // { var t = z2; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55), // (15,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17), // (15,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First(); Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString()); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void Scope_LocalFunction_Attribute_01() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_02() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_03() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_04() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_05() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_LocalFunction_Attribute_06() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_InvalidArrayDimensions01() { var text = @" public class Cls { public static void Main() { int x1 = 0; int[Test1(out int x1), x1] _1; int[Test1(out int x2), x2] x2; } static int Test1(out int x) { x = 1; return 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12), // (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27), // (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12), // (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13), // (7,27): warning CS0168: The variable 'x1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27), // (7,36): warning CS0168: The variable '_1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36), // (8,27): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27), // (8,36): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyNotAnOutLocal(model, x1Ref); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref); } [Fact] public void Scope_InvalidArrayDimensions_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using (int[] d = null) { Dummy(x1); } } void Test2() { using (int[] d = null) Dummy(x2); } void Test3() { var x3 = 11; Dummy(x3); using (int[] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 3; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16), // file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19), // file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // file.cs(14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16), // file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19), // file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51), // file.cs(21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16), // file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19), // file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51), // file.cs(30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using int[TakeOutParam(true, out var x1), x1] d = null; Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); using int[TakeOutParam(true, out var x2), x2] d = null; Dummy(x2); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9), // (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18), // (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19), // (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // (13,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15), // (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9), // (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18), // (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19), // (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46), // (21,46): warning CS0168: The variable 'x2' is declared but never used // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyNotAnOutLocal(model, x2Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true); } [Fact] public void Scope_InvalidArrayDimensions_04() { var source = @" public class X { public static void Main() { } bool Dummy(object x) {return true;} void Test1() { for (int[] a = null;;) Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); for (int[] a = null;;) Dummy(x2); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 2; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17), // file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18), // file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49), // file.cs(13,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19), // file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53), // file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17), // file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45), // file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18), // file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49), // file.cs(22,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19), // file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} unsafe void Test1() { fixed (int[TakeOutParam(true, out var x1), x1] d = null) { Dummy(x1); } } unsafe void Test2() { fixed (int[TakeOutParam(true, out var x2), x2] d = null) Dummy(x2); } unsafe void Test3() { var x3 = 11; Dummy(x3); fixed (int[TakeOutParam(true, out var x3), x3] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test1() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17), // (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19), // (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52), // (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56), // (14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test2() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17), // (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19), // (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52), // (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56), // (21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test3() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17), // (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19), // (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52), // (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56), // (30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void DeclarationInNameof_00() { var text = @" class C { public static void Main() { var x = nameof(M2(M1(out var x1), x1)).ToString(); } static int M1(out int z) => z = 1; static int M2(int a, int b) => 2; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,24): error CS8081: Expression does not have a name. // var x = nameof(M2(M1(out var x1), x1)).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "x1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(1, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DeclarationInNameof_01() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(object a, int b) => b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,83): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83), // (6,39): error CS8081: Expression does not have a name. // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30), // (6,69): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69), // (7,83): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83), // (7,39): error CS8081: Expression does not have a name. // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30), // (7,69): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02a() { var text = @" [My(C.M(nameof(C.M(out int z1)), z1), z1)] [My(C.M(nameof(C.M(out var z2)), z2), z2)] class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (2,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16), // (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5), // (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39), // (3,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16), // (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5), // (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02b() { var text1 = @" [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] "; var text2 = @" class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 }); compilation.VerifyDiagnostics( // (2,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26), // (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15), // (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49), // (3,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26), // (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15), // (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_03() { var text = @" class C { public static void Main(string[] args) { switch ((object)args.Length) { case !M(nameof(M(out int z1)), z1): System.Console.WriteLine(z1); break; case !M(nameof(M(out var z2)), z2): System.Console.WriteLine(z2); break; } } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (8,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28), // (8,18): error CS0150: A constant value is expected // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18), // (11,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28), // (11,18): error CS0150: A constant value is expected // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18), // (8,44): error CS0165: Use of unassigned local variable 'z1' // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44), // (11,44): error CS0165: Use of unassigned local variable 'z2' // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_04() { var text = @" class C { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); const bool c = (z1 + z2) == 0; public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (5,29): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29), // (5,20): error CS0133: The expression being assigned to 'C.b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20), // (6,21): error CS0103: The name 'z1' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21), // (6,26): error CS0103: The name 'z2' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26), // (4,29): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29), // (4,20): error CS0133: The expression being assigned to 'C.a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_05() { var text = @" class C { public static void Main(string[] args) { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); bool c = (z1 + z2) == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,33): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33), // (6,24): error CS0133: The expression being assigned to 'a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24), // (7,33): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33), // (7,24): error CS0133: The expression being assigned to 'b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24), // (6,49): error CS0165: Use of unassigned local variable 'z1' // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49), // (7,49): error CS0165: Use of unassigned local variable 'z2' // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_06() { var text = @" class C { public static void Main(string[] args) { string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); bool c = z1 == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,27): error CS8081: Expression does not have a name. // string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27), // (7,18): error CS0103: The name 'z1' does not exist in the current context // bool c = z1 == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "z1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, references: refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_01() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p => { weakRef.TryGetTarget(out var x); }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_02() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { weakRef.TryGetTarget(out var x); }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_03() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { void Local1 (Action<T> onNext = p3 => { weakRef.TryGetTarget(out var x); }) { } }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_04() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_05() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select (Action<T>)( p => { void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } ) ) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_06() { string source = @" class C { void M<T>() { System.Type t = typeof(int[p => { weakRef.TryGetTarget(out var x); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_07() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { weakRef.TryGetTarget(out var x); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_08() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { System.Type t3 = typeof(int[p3 => { weakRef.TryGetTarget(out var x); }]); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_09() { string source = @" class C { void M<T>() { System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_10() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[from p in y select (Action<T>)( p => { System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } ) ] ); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")] public void GetEnclosingBinderInternalRecovery_11() { var text = @" class Program { static void Main(string[] args) { foreach other(some().F(a => TestOutVar(out var x) ? x : 1)); } static void TestOutVar(out int a) { a = 0; } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, '(' expected // foreach Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16), // (7,60): error CS1515: 'in' expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60), // (7,60): error CS0230: Type and identifier are both required in a foreach statement // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60), // (7,60): error CS1525: Invalid expression term ';' // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60), // (7,60): error CS1026: ) expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xDecl = GetOutVarDeclaration(tree, "x"); var xRef = GetReferences(tree, "x", 1); VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString()); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates() { var source = @"using System; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Func<int, bool> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Expression() { var source = @"using System; using System.Linq.Expressions; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Expression<Func<int, bool>> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Query() { var source = @"using System.Linq; class C { static void M() { var c = from x in new[] { 1, 2, 3 } group x > 1 && F(out var y) && y == null by x; } static bool F(out object o) { o = null; return true; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public void SpeculativeSemanticModelWithOutDiscard() { var source = @"class C { static void F() { C.G(out _); } static void G(out object o) { o = null; } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var identifierBefore = GetReferences(tree, "G").Single(); Assert.Equal(tree, identifierBefore.Location.SourceTree); var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First(); var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);"); bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model); Assert.True(success); var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G"); Assert.Null(identifierAfter.Location.SourceTree); var info = model.GetSymbolInfo(identifierAfter); Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")] [WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")] public void GetForEachSymbolInfoWithOutVar() { var source = @"using System.Collections.Generic; public class C { void M() { foreach (var x in M2(out int i)) { } } IEnumerable<object> M2(out int j) { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachStatement); Assert.Equal("System.Object", info.ElementType.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); } [WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void DiscardAndArgList() { var text = @" using System; public class C { static void Main() { M(out _, __arglist(2, 3, true)); } static void M(out int x, __arglist) { x = 0; DumpArgs(new ArgIterator(__arglist)); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "23True"); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_01() { var text = @" public class C { static void Main() { M(1, __arglist(out int y)); M(2, __arglist(out var z)); System.Console.WriteLine(z); } static void M(int x, __arglist) { x = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(1, __arglist(out int y)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28), // (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32), // (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_02() { var text = @" public class C { static void Main() { __arglist(out int y); __arglist(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out int y); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23), // (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out int y); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9), // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // __arglist(out var z); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27), // (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out var z); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23), // (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out var z); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_01() { var text = @" public class C { static void M<T>() where T : new() { var x = new T(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z); Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)') Children(1): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_02() { var text = @" public class C { static void M<T>() where T : C, new() { var x = new T(out var z) {F1 = 1}; System.Console.WriteLine(z); } public int F1; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z) {F1 = 1}; Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z) {F1 = 1}", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}') Children(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1') Left: IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ConstructorBodyOperation() { var text = @" public class C { C() : this(out var x) { M(out var y); } => M(out var z); C (out int x){x=1;} void M (out int x){x=1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(out var x)", initializerSyntax.ToString()); compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree: @" IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation initializerOperation = model.GetOperation(initializerSyntax); Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind); Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent); Assert.Null(blockBodyOperation.Parent.Parent); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent); var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First(); Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);') Locals: Local_1: System.Int32 x Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Expression: IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MethodBodyOperation() { var text = @" public class C { int P { get {return M(out var x);} => M(out var y); } => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax); Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind); Assert.Null(expressionBodyOperation.Parent.Parent); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent); var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1); Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString()); Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900 var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);') BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyExpressionBodyOperation() { var text = @" public class C { int P => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", node3.ToString()); compilation.VerifyOperationTree(node3, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(node3).Parent); } [Fact] public void OutVarInConstructorUsedInObjectInitializer() { var source = @" public class C { public int Number { get; set; } public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { Number = i }; System.Console.WriteLine(c.Number); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] public void OutVarInConstructorUsedInCollectionInitializer() { var source = @" public class C : System.Collections.Generic.List<int> { public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { i, i, i }; System.Console.WriteLine(c[0]); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] [WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")] public void Issue49997() { var text = @" public class Cls { public static void Main() { if () .Test1().Test2(out var x1).Test3(); } } static class Ext { public static void Test3(this Cls x) {} } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last(); Assert.True(model.GetSymbolInfo(node).IsEmpty); } } internal static class OutVarTestsExtensions { internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self) { return (SingleVariableDesignationSyntax)self.Designation; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using static Roslyn.Test.Utilities.TestMetadata; using ReferenceEqualityComparer = Roslyn.Utilities.ReferenceEqualityComparer; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.OutVar)] public class OutVarTests : CompilingTestBase { [Fact] public void OldVersion() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,29): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [WorkItem(12182, "https://github.com/dotnet/roslyn/issues/12182")] [WorkItem(16348, "https://github.com/dotnet/roslyn/issues/16348")] public void DiagnosticsDifferenceBetweenLanguageVersions_01() { var text = @" public class Cls { public static void Test1() { Test(out int x1); } public static void Test2() { var x = new Cls(out int x2); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,22): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // Test(out int x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x1").WithArguments("out variable declaration", "7.0").WithLocation(6, 22), // (11,33): error CS8059: Feature 'out variable declaration' is not available in C# 6. Please use language version 7.0 or greater. // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "x2").WithArguments("out variable declaration", "7.0").WithLocation(11, 33), // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test' does not exist in the current context // Test(out int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(6, 9), // (11,21): error CS1729: 'Cls' does not contain a constructor that takes 1 arguments // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Cls").WithArguments("Cls", "1").WithLocation(11, 21), // (11,29): error CS0165: Use of unassigned local variable 'x2' // var x = new Cls(out int x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x2").WithArguments("x2").WithLocation(11, 29) ); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); x2Decl = GetOutVarDeclaration(tree, "x2"); //VerifyModelForOutVar(model, x2Decl); Probably fails due to https://github.com/dotnet/roslyn/issues/16348 VerifyModelForOutVarWithoutDataFlow(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_01() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_02() { var text = @" public class Cls { public static void Main() { Test1(out (var x1, var x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (var x1, var x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, var x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_03() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, long x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,28): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, long x2)").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,28): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, long x2)); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_04() { var text = @" public class Cls { public static void Main() { Test1(out (int x1, (long x2, byte x3))); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilationWithMscorlib40(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,20): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 20), // (6,29): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "long x2").WithLocation(6, 29), // (6,38): error CS8185: A declaration is not allowed in this context. // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "byte x3").WithLocation(6, 38), // (6,28): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(long x2, byte x3)").WithArguments("System.ValueTuple`2").WithLocation(6, 28), // (6,19): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int x1, (long x2, byte x3))").WithArguments("System.ValueTuple`2").WithLocation(6, 19), // (6,20): error CS0165: Use of unassigned local variable 'x1' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(6, 20), // (6,29): error CS0165: Use of unassigned local variable 'x2' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x2").WithArguments("x2").WithLocation(6, 29), // (6,38): error CS0165: Use of unassigned local variable 'x3' // Test1(out (int x1, (long x2, byte x3))); Diagnostic(ErrorCode.ERR_UseDefViolation, "byte x3").WithArguments("x3").WithLocation(6, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); VerifyModelForDeclarationVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForDeclarationVarWithoutDataFlow(model, x3Decl, x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_05() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2, x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2, x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_06() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; Test1(out var (x1)); System.Console.WriteLine(F1); } static ref int var(object x) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1)").WithLocation(8, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_07() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, x2: x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2: x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2: x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_08() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (ref x1, x2)); System.Console.WriteLine(F1); } static ref int var(ref object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (ref x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (ref x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_09() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var (x1, (x2))); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (x2))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (x2))").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_10() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out var ((x1), x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var ((x1), x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var ((x1), x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_11() { var text = @" public class Cls { public static void Main() { Test1(out var (x1, x2)); System.Console.WriteLine(x1); System.Console.WriteLine(x2); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); compilation.VerifyDiagnostics( // (6,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(6, 19), // (6,24): error CS0103: The name 'x1' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 24), // (6,28): error CS0103: The name 'x2' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 28), // (6,19): error CS0103: The name 'var' does not exist in the current context // Test1(out var (x1, x2)); Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 19), // (7,34): error CS0103: The name 'x1' does not exist in the current context // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 34), // (8,34): error CS0103: The name 'x2' does not exist in the current context // System.Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(8, 34) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_12() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(out M1 (x1, x2)); System.Console.WriteLine(F1); } static ref int M1(object x1, object x2) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_13() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(ref var (x1, x2)); System.Console.WriteLine(F1); } static ref int var(object x1, object x2) { return ref F1; } static object Test1(ref int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(ref var (x1, x2)); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, x2)").WithLocation(9, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_14() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; Test1(var (x1, x2)); System.Console.WriteLine(F1); } static int var(object x1, object x2) { F1 = 123; return 124; } static object Test1(int x) { System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"124 123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_15() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out M1 (x1, (x2, x3))); System.Console.WriteLine(F1); } static ref int M1(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "123"); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] [WorkItem(13148, "https://github.com/dotnet/roslyn/issues/13148")] public void OutVarDeconstruction_16() { var text = @" public class Cls { private static int F1; public static void Main() { object x1 = null; object x2 = null; object x3 = null; Test1(out var (x1, (a: x2, b: x3))); System.Console.WriteLine(F1); } static ref int var(object x, object y) { return ref F1; } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,19): error CS8199: The syntax 'var (...)' as an lvalue is reserved. // Test1(out var (x1, (a: x2, b: x3))); Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var (x1, (a: x2, b: x3))").WithLocation(11, 19) ); Assert.False(compilation.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any()); } private static IdentifierNameSyntax GetReference(SyntaxTree tree, string name) { return GetReferences(tree, name).Single(); } private static IdentifierNameSyntax[] GetReferences(SyntaxTree tree, string name, int count) { var nameRef = GetReferences(tree, name).ToArray(); Assert.Equal(count, nameRef.Length); return nameRef; } internal static IEnumerable<IdentifierNameSyntax> GetReferences(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == name); } private static IEnumerable<DeclarationExpressionSyntax> GetDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == name); } private static DeclarationExpressionSyntax GetDeclaration(SyntaxTree tree, string name) { return GetDeclarations(tree, name).Single(); } internal static DeclarationExpressionSyntax GetOutVarDeclaration(SyntaxTree tree, string name) { return GetOutVarDeclarations(tree, name).Single(); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree, string name) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration() && p.Identifier().ValueText == name); } private static IEnumerable<DiscardDesignationSyntax> GetDiscardDesignations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DiscardDesignationSyntax>(); } private static IEnumerable<IdentifierNameSyntax> GetDiscardIdentifiers(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(i => i.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken); } private static IEnumerable<DeclarationExpressionSyntax> GetOutVarDeclarations(SyntaxTree tree) { return tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.IsOutVarDeclaration()); } [Fact] public void Simple_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1); int x2; Test3(out x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVarWithoutDataFlow(model, decl, isShadowed: false, references: references); } private static void VerifyModelForOutVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isShadowed, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: isShadowed, verifyDataFlow: false, references: references); } private static void VerifyModelForDeclarationVarWithoutDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: false, expectedLocalKind: LocalDeclarationKind.DeclarationExpressionVariable, references: references); } internal static void VerifyModelForOutVar(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode(SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: references); } private static void VerifyModelForOutVarInNotExecutableCode( SemanticModel model, DeclarationExpressionSyntax decl, IdentifierNameSyntax reference) { VerifyModelForOutVar( model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, verifyDataFlow: true, references: reference); } private static void VerifyModelForOutVar( SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, bool isShadowed, bool verifyDataFlow = true, LocalDeclarationKind expectedLocalKind = LocalDeclarationKind.OutVariable, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax); Assert.NotNull(symbol); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(expectedLocalKind, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.False(((ILocalSymbol)symbol).IsFixed); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var other = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single(); if (isShadowed) { Assert.NotEqual(symbol, other); } else { Assert.Same(symbol, other); } Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: local.Type); foreach (var reference in references) { Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } if (verifyDataFlow) { VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol); } } private static void AssertInfoForDeclarationExpressionSyntax( SemanticModel model, DeclarationExpressionSyntax decl, ISymbol expectedSymbol = null, ITypeSymbol expectedType = null ) { var symbolInfo = model.GetSymbolInfo(decl); Assert.Equal(expectedSymbol, symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(symbolInfo, ((CSharpSemanticModel)model).GetSymbolInfo(decl)); var typeInfo = model.GetTypeInfo(decl); Assert.Equal(expectedType, typeInfo.Type); // skip cases where operation is not supported AssertTypeFromOperation(model, expectedType, decl); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.Equal(expectedType, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(decl)); // Note: the following assertion is not, in general, correct for declaration expressions, // even though this helper is used to handle declaration expressions. // However, the tests that use this helper have been carefully crafted to avoid // triggering failure of the assertion. See also https://github.com/dotnet/roslyn/issues/17463 Assert.True(model.GetConversion(decl).IsIdentity); var typeSyntax = decl.Type; Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax)); Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax)); ITypeSymbol expected = expectedSymbol?.GetTypeOrReturnType(); if (expected?.IsErrorType() != false) { Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol); } else { Assert.Equal(expected, model.GetSymbolInfo(typeSyntax).Symbol); } typeInfo = model.GetTypeInfo(typeSyntax); Assert.Equal(expected, typeInfo.Type); Assert.Equal(expected, typeInfo.ConvertedType); Assert.Equal(typeInfo, ((CSharpSemanticModel)model).GetTypeInfo(typeSyntax)); Assert.True(model.GetConversion(typeSyntax).IsIdentity); var conversion = model.ClassifyConversion(decl, model.Compilation.ObjectType, false); Assert.False(conversion.Exists); Assert.Equal(conversion, model.ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, model.ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, false)); Assert.Equal(conversion, ((CSharpSemanticModel)model).ClassifyConversion(decl.Position, decl, model.Compilation.ObjectType, true)); Assert.Null(model.GetDeclaredSymbol(decl)); } private static void AssertTypeFromOperation(SemanticModel model, ITypeSymbol expectedType, DeclarationExpressionSyntax decl) { // see https://github.com/dotnet/roslyn/issues/23006 and https://github.com/dotnet/roslyn/issues/23007 for more detail // unlike GetSymbolInfo or GetTypeInfo, GetOperation doesn't use SemanticModel's recovery mode. // what that means is that GetOperation might return null for ones GetSymbol/GetTypeInfo do return info from // error recovery mode var typeofExpression = decl.Ancestors().OfType<TypeOfExpressionSyntax>().FirstOrDefault(); if (typeofExpression?.Type?.FullSpan.Contains(decl.Span) == true) { // invalid syntax case where operation is not supported return; } Assert.Equal(expectedType, model.GetOperation(decl)?.Type); } private static void VerifyDataFlow(SemanticModel model, DeclarationExpressionSyntax decl, bool isDelegateCreation, bool isExecutableCode, IdentifierNameSyntax[] references, ISymbol symbol) { var dataFlowParent = decl.Parent.Parent.Parent as ExpressionSyntax; if (dataFlowParent == null) { if (isExecutableCode || !(decl.Parent.Parent.Parent is VariableDeclaratorSyntax)) { Assert.IsAssignableFrom<ConstructorInitializerSyntax>(decl.Parent.Parent.Parent); } return; } if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); return; } var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (isExecutableCode) { Assert.True(dataFlow.Succeeded); Assert.True(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); if (!isDelegateCreation) { Assert.True(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.True(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); var flowsIn = FlowsIn(dataFlowParent, decl, references); Assert.Equal(flowsIn, dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(flowsIn, dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(FlowsOut(dataFlowParent, decl, references), dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(ReadOutside(dataFlowParent, references), dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.Equal(WrittenOutside(dataFlowParent, references), dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } private static void VerifyModelForOutVarDuplicateInSameScope(SemanticModel model, DeclarationExpressionSyntax decl) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(LocalDeclarationKind.OutVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single()); Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText)); var local = (ILocalSymbol)symbol; AssertInfoForDeclarationExpressionSyntax(model, decl, local, local.Type); } private static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static void VerifyNotAnOutField(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; Assert.NotEqual(SymbolKind.Field, symbol.Kind); Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } internal static void VerifyNotAnOutLocal(SemanticModel model, IdentifierNameSyntax reference) { var symbol = model.GetSymbolInfo(reference).Symbol; if (symbol.Kind == SymbolKind.Local) { var local = symbol.GetSymbol<SourceLocalSymbol>(); var parent = local.IdentifierToken.Parent; Assert.Empty(parent.Ancestors().OfType<DeclarationExpressionSyntax>().Where(e => e.IsOutVarDeclaration())); if (parent.Kind() == SyntaxKind.VariableDeclarator) { var parent1 = ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)parent).Parent).Parent; switch (parent1.Kind()) { case SyntaxKind.FixedStatement: case SyntaxKind.ForStatement: case SyntaxKind.UsingStatement: break; default: Assert.Equal(SyntaxKind.LocalDeclarationStatement, parent1.Kind()); break; } } } Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Single()); Assert.True(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText)); } private static SingleVariableDesignationSyntax GetVariableDesignation(DeclarationExpressionSyntax decl) { return (SingleVariableDesignationSyntax)decl.Designation; } private static bool FlowsIn(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (dataFlowParent.Span.Contains(reference.Span) && reference.SpanStart > decl.SpanStart) { if (IsRead(reference)) { return true; } } } return false; } private static bool IsRead(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.OutKeyword) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left != reference) { return true; } break; default: return true; } return false; } private static bool ReadOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsRead(reference)) { return true; } } } return false; } private static bool FlowsOut(ExpressionSyntax dataFlowParent, DeclarationExpressionSyntax decl, IdentifierNameSyntax[] references) { ForStatementSyntax forStatement; if ((forStatement = decl.Ancestors().OfType<ForStatementSyntax>().FirstOrDefault()) != null && forStatement.Incrementors.Span.Contains(decl.Position) && forStatement.Statement.DescendantNodes().OfType<ForStatementSyntax>().Any(f => f.Condition == null)) { return false; } var containingStatement = decl.Ancestors().OfType<StatementSyntax>().FirstOrDefault(); var containingReturnOrThrow = containingStatement as ReturnStatementSyntax ?? (StatementSyntax)(containingStatement as ThrowStatementSyntax); MethodDeclarationSyntax methodDeclParent; if (containingReturnOrThrow != null && decl.Identifier().ValueText == "x1" && ((methodDeclParent = containingReturnOrThrow.Parent.Parent as MethodDeclarationSyntax) == null || methodDeclParent.Body.Statements.First() != containingReturnOrThrow)) { return false; } foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span) && (containingReturnOrThrow == null || containingReturnOrThrow.Span.Contains(reference.SpanStart)) && (reference.SpanStart > decl.SpanStart || (containingReturnOrThrow == null && reference.Ancestors().OfType<DoStatementSyntax>().Join( decl.Ancestors().OfType<DoStatementSyntax>(), d => d, d => d, (d1, d2) => true).Any()))) { if (IsRead(reference)) { return true; } } } return false; } private static bool WrittenOutside(ExpressionSyntax dataFlowParent, IdentifierNameSyntax[] references) { foreach (var reference in references) { if (!dataFlowParent.Span.Contains(reference.Span)) { if (IsWrite(reference)) { return true; } } } return false; } private static bool IsWrite(IdentifierNameSyntax reference) { switch (reference.Parent.Kind()) { case SyntaxKind.Argument: if (((ArgumentSyntax)reference.Parent).RefOrOutKeyword.Kind() != SyntaxKind.None) { return true; } break; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: if (((AssignmentExpressionSyntax)reference.Parent).Left == reference) { return true; } break; case SyntaxKind.PreIncrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.PostDecrementExpression: return true; default: return false; } return false; } [Fact] public void Simple_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Int32 x1), x1); int x2 = 0; Test3(x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } static void Test3(int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_03() { var text = @" public class Cls { public static void Main() { Test2(Test1(out (int, int) x1), x1); } static object Test1(out (int, int) x) { x = (123, 124); return null; } static void Test2(object x, (int, int) y) { System.Console.WriteLine(y); } } namespace System { // struct with two values public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } } } " + TestResources.NetFX.ValueTuple.tupleattributes_cs; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"{123, 124}").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_04() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.Collections.Generic.IEnumerable<System.Int32> x1), x1); } static object Test1(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = new System.Collections.Generic.List<System.Int32>(); return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Collections.Generic.List`1[System.Int32]").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, out x1), x1); } static object Test1(out int x, out int y) { x = 123; y = 124; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1, x1 = 124), x1); } static object Test1(out int x, int y) { x = 123; return null; } static void Test2(object x, int y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_07() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), x1, x1 = 124); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, int y, int z) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1", 2); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_08() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), ref x1); int x2 = 0; Test3(ref x2); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, ref int y) { System.Console.WriteLine(y); } static void Test3(ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Ref = GetReference(tree, "x2"); Assert.Null(model.GetDeclaredSymbol(x2Ref)); Assert.Null(model.GetDeclaredSymbol((ArgumentSyntax)x2Ref.Parent)); } [Fact] public void Simple_09() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int x1), out x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, out int y) { y = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_10() { var text = @" public class Cls { public static void Main() { Test2(Test1(out dynamic x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Simple_11() { var text = @" public class Cls { public static void Main() { Test2(Test1(out int[] x1), x1); } static object Test1(out int[] x) { x = new [] {123}; return null; } static void Test2(object x, int[] y) { System.Console.WriteLine(y[0]); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_01() { var text = @" public class Cls { public static void Main() { int x1 = 0; Test1(out int x1); Test2(Test1(out int x2), out int x2); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS0128: A local variable named 'x1' is already defined in this scope // Test1(out int x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 23), // (9,29): error CS0128: A local variable named 'x2' is already defined in this scope // out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(9, 29), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13) ); } [Fact] public void Scope_02() { var text = @" public class Cls { public static void Main() { Test2(x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(object y, object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 15) ); } [Fact] public void Scope_03() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out int x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_04() { var text = @" public class Cls { public static void Main() { Test1(out int x1); System.Console.WriteLine(x1); } static object Test1(out int x) { x = 1; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_05() { var text = @" public class Cls { public static void Main() { Test2(out x1, Test1(out var x1)); } static object Test1(out int x) { x = 1; return null; } static void Test2(out int y, object x) { y = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,19): error CS0841: Cannot use local variable 'x1' before it is declared // Test2(out x1, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 19) ); } [Fact] public void Scope_Attribute_01() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_02() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out int x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out int x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_03() { var source = @" public class X { public static void Main() { } [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 15), // (9,15): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 15), // (11,40): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 40), // (10,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 15), // (14,37): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 37), // (13,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p1 = TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 16), // (14,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 16), // (15,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(p = TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 15), // (16,15): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 15), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_Attribute_04() { var source = @" public class X { public static void Main() { } [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x3) && x3 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x3) && x3 > 0").WithLocation(8, 11), // (9,11): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(9, 11), // (11,36): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(11, 36), // (10,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_BadAttributeArgument, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithLocation(10, 11), // (14,32): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(14, 32), // (13,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x6) && x6 > 0, Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(13, 11), // (14,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x6) && x6 > 0").WithLocation(14, 11), // (15,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Test(TakeOutParam(out var x7) && x7 > 0)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "TakeOutParam(out var x7) && x7 > 0").WithLocation(15, 11), // (16,11): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(16, 11), // (17,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void AttributeArgument_01() { var source = @" public class X { [Test(out var x3)] [Test(out int x4)] [Test(p: out var x5)] [Test(p: out int x6)] public static void Main() { } } class Test : System.Attribute { public Test(out int p) { p = 100; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (4,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out var x3)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(4, 11), // (4,19): error CS1003: Syntax error, ',' expected // [Test(out var x3)] Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(4, 19), // (5,11): error CS1041: Identifier expected; 'out' is a keyword // [Test(out int x4)] Diagnostic(ErrorCode.ERR_IdentifierExpectedKW, "out").WithArguments("", "out").WithLocation(5, 11), // (5,15): error CS1525: Invalid expression term 'int' // [Test(out int x4)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(5, 15), // (5,19): error CS1003: Syntax error, ',' expected // [Test(out int x4)] Diagnostic(ErrorCode.ERR_SyntaxError, "x4").WithArguments(",", "").WithLocation(5, 19), // (6,14): error CS1525: Invalid expression term 'out' // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 14), // (6,14): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "var").WithArguments(",", "").WithLocation(6, 18), // (6,22): error CS1003: Syntax error, ',' expected // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_SyntaxError, "x5").WithArguments(",", "").WithLocation(6, 22), // (7,14): error CS1525: Invalid expression term 'out' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(7, 14), // (7,14): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(7, 14), // (7,18): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(7, 18), // (7,18): error CS1525: Invalid expression term 'int' // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_SyntaxError, "x6").WithArguments(",", "").WithLocation(7, 22), // (4,15): error CS0103: The name 'var' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 15), // (4,19): error CS0103: The name 'x3' does not exist in the current context // [Test(out var x3)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(4, 19), // (4,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out var x3)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out var x3)").WithArguments("Test", "2").WithLocation(4, 6), // (5,19): error CS0103: The name 'x4' does not exist in the current context // [Test(out int x4)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(5, 19), // (5,6): error CS1729: 'Test' does not contain a constructor that takes 2 arguments // [Test(out int x4)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(out int x4)").WithArguments("Test", "2").WithLocation(5, 6), // (6,18): error CS0103: The name 'var' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 18), // (6,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "var").WithArguments("7.2").WithLocation(6, 18), // (6,22): error CS0103: The name 'x5' does not exist in the current context // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(6, 22), // (6,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out var x5)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out var x5)").WithArguments("Test", "3").WithLocation(6, 6), // (7,18): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "int").WithArguments("7.2").WithLocation(7, 18), // (7,22): error CS0103: The name 'x6' does not exist in the current context // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(7, 22), // (7,6): error CS1729: 'Test' does not contain a constructor that takes 3 arguments // [Test(p: out int x6)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test(p: out int x6)").WithArguments("Test", "3").WithLocation(7, 6) ); var tree = compilation.SyntaxTrees.Single(); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); Assert.False(GetOutVarDeclarations(tree, "x4").Any()); Assert.False(GetOutVarDeclarations(tree, "x5").Any()); Assert.False(GetOutVarDeclarations(tree, "x6").Any()); } [Fact] public void Scope_Catch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } } void Test4() { var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Scope_Catch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { try {} catch when (TakeOutParam(out int x1) && x1 > 0) { Dummy(x1); } } void Test4() { int x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out int x4) && x4 > 0) { Dummy(x4); } } void Test6() { try {} catch when (x6 && TakeOutParam(out int x6)) { Dummy(x6); } } void Test7() { try {} catch when (TakeOutParam(out int x7) && x7 > 0) { int x7 = 12; Dummy(x7); } } void Test8() { try {} catch when (TakeOutParam(out int x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); } void Test9() { try {} catch when (TakeOutParam(out int x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out int x9) && x9 > 0) // 2 { Dummy(x9); } } } void Test10() { try {} catch when (TakeOutParam(y10, out int x10)) { int y10 = 12; Dummy(y10); } } //void Test11() //{ // try {} // catch when (TakeOutParam(y11, out int x11) // { // let y11 = 12; // Dummy(y11); // } //} void Test14() { try {} catch when (Dummy(TakeOutParam(out int x14), TakeOutParam(out int x14), // 2 x14)) { Dummy(x14); } } void Test15() { try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out int x15), x15)) { Dummy(x15); } } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(25, 42), // (34,21): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out int x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(34, 21), // (45,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(45, 17), // (58,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(58, 34), // (68,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out int x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(68, 46), // (78,34): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out int x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(78, 34), // (99,48): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(out int x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 48), // (110,48): error CS0128: A local variable named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out int x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(110, 48) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Catch_01_ExplicitType() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out System.Exception x1), x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Scope_ConstructorInitializers_01() { var source = @" public class X { public static void Main() { } X(byte x) : this(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : this(x4 && TakeOutParam(4, out int x4)) {} X(short x) : this(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : this(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : this(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : this(x7, 2) {} void Test73() { Dummy(x7, 3); } X(params object[] x) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : this(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : this(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_02() { var source = @" public class X : Y { public static void Main() { } X(byte x) : base(TakeOutParam(3, out int x3) && x3 > 0) {} X(sbyte x) : base(x4 && TakeOutParam(4, out int x4)) {} X(short x) : base(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} X(ushort x) : base(TakeOutParam(6, out int x6) && x6 > 0, TakeOutParam(6, out int x6) && x6 > 0) // 2 {} X(int x) : base(TakeOutParam(7, out int x7) && x7 > 0) {} X(uint x) : base(x7, 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } public class Y { public Y(params object[] x) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0841: Cannot use local variable 'x4' before it is declared // : base(x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(13, 16), // (18,41): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(18, 41), // (24,40): error CS0128: A local variable named 'x6' is already defined in this scope // TakeOutParam(6, out int x6) && x6 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(24, 40), // (30,16): error CS0103: The name 'x7' does not exist in the current context // : base(x7, 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(30, 16), // (32,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(32, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_ConstructorInitializers_03() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D { public D(int o) : this(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_04() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(12); } } class D : C { public D(int o) : base(TakeOutParam(o, out int x1) && x1 >= 5) { Console.WriteLine(x1); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"False 1 True 10 True 12 ").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_05() { var source = @"using System; class D { public D(int o) : this(SpeculateHere) { } public D(bool b) { Console.WriteLine(b); } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.ThisConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_ConstructorInitializers_06() { var source = @"using System; class D : C { public D(int o) : base(SpeculateHere) { } static bool TakeOutParam(int y, out int x) { x = y; return true; } } class C { public C(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); ArgumentListSyntax arguments = SyntaxFactory.ParseArgumentList(@"(TakeOutParam(o, out int x1) && x1 >= 5)"); var initializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, arguments); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, initializer, out model); Assert.True(success); Assert.NotNull(model); tree = initializer.SyntaxTree; var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var initializerOperation = model.GetOperation(initializer); Assert.Null(initializerOperation.Parent.Parent.Parent); VerifyOperationTree(compilation, initializerOperation.Parent.Parent, @" IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Expression: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: '(TakeOutPar ... && x1 >= 5)') Children(1): IInvocationOperation ( C..ctor(System.Boolean b)) (OperationKind.Invocation, Type: System.Void) (Syntax: ':base(TakeO ... && x1 >= 5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ':base(TakeO ... && x1 >= 5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'TakeOutPara ... && x1 >= 5') IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... && x1 >= 5') Left: IInvocationOperation (System.Boolean D.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'o') IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'o') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x1 >= 5') Left: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] public void Scope_ConstructorInitializers_07() { var source = @" public class X : Y { public static void Main() { } X(byte x3) : base(TakeOutParam(3, out var x3)) {} X(sbyte x) : base(TakeOutParam(4, out var x4)) { int x4 = 1; System.Console.WriteLine(x4); } X(ushort x) : base(TakeOutParam(51, out var x5)) => Dummy(TakeOutParam(52, out var x5), x5); X(short x) : base(out int x6, x6) {} X(uint x) : base(out var x7, x7) {} X(int x) : base(TakeOutParam(out int x8, x8)) {} X(ulong x) : base(TakeOutParam(out var x9, x9)) {} bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } public class Y { public Y(params object[] x) {} public Y(out int x, int y) { x = y; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // : base(TakeOutParam(3, out var x3)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(9, 40), // (15,13): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // int x4 = 1; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 13), // (21,39): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // => Dummy(TakeOutParam(52, out var x5), x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 39), // (24,28): error CS0165: Use of unassigned local variable 'x6' // : base(out int x6, x6) Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(24, 28), // (28,28): error CS8196: Reference to an implicitly-typed out variable 'x7' is not permitted in the same argument list. // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x7").WithArguments("x7").WithLocation(28, 28), // (28,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // : base(out var x7, x7) Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x7").WithArguments("1", "out").WithLocation(28, 20), // (32,41): error CS0165: Use of unassigned local variable 'x8' // : base(TakeOutParam(out int x8, x8)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(32, 41), // (36,41): error CS8196: Reference to an implicitly-typed out variable 'x9' is not permitted in the same argument list. // : base(TakeOutParam(out var x9, x9)) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x9").WithArguments("x9").WithLocation(36, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").Single(); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVarWithoutDataFlow(model, x9Decl, x9Ref); } [Fact] public void Scope_Do_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { do { Dummy(x1); } while (TakeOutParam(true, out var x1) && x1); } void Test2() { do Dummy(x2); while (TakeOutParam(true, out var x2) && x2); } void Test4() { var x4 = 11; Dummy(x4); do Dummy(x4); while (TakeOutParam(true, out var x4) && x4); } void Test6() { do Dummy(x6); while (x6 && TakeOutParam(true, out var x6)); } void Test7() { do { var x7 = 12; Dummy(x7); } while (TakeOutParam(true, out var x7) && x7); } void Test8() { do Dummy(x8); while (TakeOutParam(true, out var x8) && x8); System.Console.WriteLine(x8); } void Test9() { do { Dummy(x9); do Dummy(x9); while (TakeOutParam(true, out var x9) && x9); // 2 } while (TakeOutParam(true, out var x9) && x9); } void Test10() { do { var y10 = 12; Dummy(y10); } while (TakeOutParam(y10, out var x10)); } //void Test11() //{ // do // { // let y11 = 12; // Dummy(y11); // } // while (TakeOutParam(y11, out var x11)); //} void Test12() { do var y12 = 12; while (TakeOutParam(y12, out var x12)); } //void Test13() //{ // do // let y13 = 12; // while (TakeOutParam(y13, out var x13)); //} void Test14() { do { Dummy(x14); } while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (97,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(97, 13), // (14,19): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(14, 19), // (22,19): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(22, 19), // (33,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(33, 43), // (32,19): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy(x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(32, 19), // (40,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(40, 16), // (39,19): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(39, 19), // (47,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(47, 17), // (56,19): error CS0841: Cannot use local variable 'x8' before it is declared // Dummy(x8); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x8").WithArguments("x8").WithLocation(56, 19), // (59,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(59, 34), // (66,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(66, 19), // (69,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9); // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(69, 47), // (68,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(68, 23), // (81,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(81, 29), // (98,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)); Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(98, 29), // (97,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(97, 17), // (115,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(115, 46), // (112,19): error CS0841: Cannot use local variable 'x14' before it is declared // Dummy(x14); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x14").WithArguments("x14").WithLocation(112, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[1]); VerifyNotAnOutLocal(model, x7Ref[0]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[1]); VerifyNotAnOutLocal(model, y10Ref[0]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Do_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) do { } while (TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Do_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (DoStatementSyntax)SyntaxFactory.ParseStatement(@" do {} while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { int f = 1; do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, TakeOutParam((f ? 1 : 2), out int x1), x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1) && false); if (f) { do ; while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, TakeOutParam(f++, out var x1), x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { } bool Test3(object o) => TakeOutParam(o, out int x3) && x3 > 0; bool Test4(object o) => x4 && TakeOutParam(o, out int x4); bool Test5(object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; bool Test61 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test62 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool Test71(object o) => TakeOutParam(o, out int x7) && x7 > 0; void Test72() => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test11(object x11) => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,29): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4(object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 29), // (13,67): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 67), // (19,28): error CS0103: The name 'x7' does not exist in the current context // void Test72() => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 28), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,56): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool Test11(object x11) => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 56) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(14214, "https://github.com/dotnet/roslyn/issues/14214")] public void Scope_ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test3() { bool f (object o) => TakeOutParam(o, out int x3) && x3 > 0; f(null); } void Test4() { bool f (object o) => x4 && TakeOutParam(o, out int x4); f(null); } void Test5() { bool f (object o1, object o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0; f(null, null); } void Test6() { bool f1 (object o) => TakeOutParam(o, out int x6) && x6 > 0; bool f2 (object o) => TakeOutParam(o, out int x6) && x6 > 0; f1(null); f2(null); } void Test7() { Dummy(x7, 1); bool f (object o) => TakeOutParam(o, out int x7) && x7 > 0; Dummy(x7, 2); f(null); } void Test11() { var x11 = 11; Dummy(x11); bool f (object o) => TakeOutParam(o, out int x11) && x11 > 0; f(null); } void Test12() { bool f (object o) => TakeOutParam(o, out int x12) && x12 > 0; var x12 = 11; Dummy(x12); f(null); } System.Action Test13() { return () => { bool f (object o) => TakeOutParam(o, out int x13) && x13 > 0; f(null); }; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (18,30): error CS0841: Cannot use local variable 'x4' before it is declared // bool f (object o) => x4 && TakeOutParam(o, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(18, 30), // (25,67): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(25, 67), // (39,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(39, 15), // (43,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(43, 15), // (51,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(51, 54), // (58,54): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool f (object o) => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(58, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); // Data flow for the following disabled due to https://github.com/dotnet/roslyn/issues/14214 var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarWithoutDataFlow(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x11Decl, x11Ref[1]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").Single(); VerifyModelForOutVarWithoutDataFlow(model, x13Decl, x13Ref); } [Fact] public void ExpressionBodiedLocalFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out int x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedLocalFunctions_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { bool f() => TakeOutParam(1, out var x1) && Dummy(x1); return f(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void Scope_ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { } bool Test3 => TakeOutParam(3, out int x3) && x3 > 0; bool Test4 => x4 && TakeOutParam(4, out int x4); bool Test5 => TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 => TakeOutParam(6, out int x6) && x6 > 0; bool Test62 => TakeOutParam(6, out int x6) && x6 > 0; bool Test71 => TakeOutParam(7, out int x7) && x7 > 0; bool Test72 => Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool this[object x11] => TakeOutParam(1, out int x11) && x11 > 0; bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,19): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 => x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 19), // (13,44): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 44), // (19,26): error CS0103: The name 'x7' does not exist in the current context // bool Test72 => Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 26), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,54): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // bool this[object x11] => TakeOutParam(1, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(22, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").Single(); VerifyModelForOutVar(model, x11Decl, x11Ref); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out int x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void ExpressionBodiedProperties_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => TakeOutParam(2, out var x1) && Dummy(x1); bool this[object x] => TakeOutParam(1, out var x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void Scope_ExpressionStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { Dummy(TakeOutParam(true, out var x1), x1); { Dummy(TakeOutParam(true, out var x1), x1); } Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ExpressionStatement_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) Test2(Test1(out int x1), x1); if (test) { Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_ExpressionStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ExpressionStatement_04() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Scope_FieldInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 = x4 && TakeOutParam(4, out int x4); bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27), // (22,57): error CS0103: The name 'x8' does not exist in the current context // bool Test81 = TakeOutParam(8, out int x8), Test82 = x8 > 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(22, 57), // (23,19): error CS0103: The name 'x9' does not exist in the current context // bool Test91 = x9 > 0, Test92 = TakeOutParam(9, out int x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(23, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReference(tree, "x8"); VerifyModelForOutVar(model, x8Decl); VerifyNotInScope(model, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReference(tree, "x9"); VerifyNotInScope(model, x9Ref); VerifyModelForOutVar(model, x9Decl); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_FieldInitializers_02() { var source = @"using static Test; public enum X { Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0, Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Test72 = x7, } class Test { public static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'x4' before it is declared // Test4 = x4 && TakeOutParam(4, out int x4) ? 1 : 0, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 13), // (9,38): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 38), // (8,13): error CS0133: The expression being assigned to 'X.Test5' must be constant // Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0 ? 1 : 0").WithArguments("X.Test5").WithLocation(8, 13), // (12,14): error CS0133: The expression being assigned to 'X.Test61' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test61").WithLocation(12, 14), // (12,70): error CS0133: The expression being assigned to 'X.Test62' must be constant // Test61 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0 ? 1 : 0").WithArguments("X.Test62").WithLocation(12, 70), // (14,14): error CS0133: The expression being assigned to 'X.Test71' must be constant // Test71 = TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0 ? 1 : 0").WithArguments("X.Test71").WithLocation(14, 14), // (15,14): error CS0103: The name 'x7' does not exist in the current context // Test72 = x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 14), // (4,13): error CS0133: The expression being assigned to 'X.Test3' must be constant // Test3 = TakeOutParam(3, out int x3) ? x3 : 0, Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) ? x3 : 0").WithArguments("X.Test3").WithLocation(4, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: X.Test3) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... 3) ? x3 : 0') Locals: Local_1: System.Int32 x3 IConditionalOperation (OperationKind.Conditional, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... 3) ? x3 : 0') Condition: IInvocationOperation (System.Boolean Test.TakeOutParam(System.Object y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '3') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_FieldInitializers_03() { var source = @" public class X { public static void Main() { } const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; const bool Test4 = x4 && TakeOutParam(4, out int x4); const bool Test5 = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; const bool Test72 = x7 > 2; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,24): error CS0133: The expression being assigned to 'X.Test3' must be constant // const bool Test3 = TakeOutParam(3, out int x3) && x3 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("X.Test3").WithLocation(8, 24), // (10,24): error CS0841: Cannot use local variable 'x4' before it is declared // const bool Test4 = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 24), // (13,49): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 49), // (12,24): error CS0133: The expression being assigned to 'X.Test5' must be constant // const bool Test5 = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_NotConstantExpression, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("X.Test5").WithLocation(12, 24), // (16,25): error CS0133: The expression being assigned to 'X.Test61' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test61").WithLocation(16, 25), // (16,73): error CS0133: The expression being assigned to 'X.Test62' must be constant // const bool Test61 = TakeOutParam(6, out int x6) && x6 > 0, Test62 = TakeOutParam(6, out int x6) && x6 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("X.Test62").WithLocation(16, 73), // (18,25): error CS0133: The expression being assigned to 'X.Test71' must be constant // const bool Test71 = TakeOutParam(7, out int x7) && x7 > 0; Diagnostic(ErrorCode.ERR_NotConstantExpression, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("X.Test71").WithLocation(18, 25), // (19,25): error CS0103: The name 'x7' does not exist in the current context // const bool Test72 = x7 > 2; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 25), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_FieldInitializers_04() { var source = @" class X : Y { public static void Main() { } bool Test3 = TakeOutParam(out int x3, x3); bool Test4 = TakeOutParam(out var x4, x4); bool Test5 = TakeOutParam(out int x5, 5); X() : this(x5) { System.Console.WriteLine(x5); } X(object x) : base(x5) => System.Console.WriteLine(x5); static bool Test6 = TakeOutParam(out int x6, 6); static X() { System.Console.WriteLine(x6); } static bool TakeOutParam(out int x, int y) { x = 123; return true; } } class Y { public Y(object y) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,43): error CS0165: Use of unassigned local variable 'x3' // bool Test3 = TakeOutParam(out int x3, x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(8, 43), // (10,43): error CS8196: Reference to an implicitly-typed out variable 'x4' is not permitted in the same argument list. // bool Test4 = TakeOutParam(out var x4, x4); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x4").WithArguments("x4").WithLocation(10, 43), // (15,12): error CS0103: The name 'x5' does not exist in the current context // : this(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(15, 12), // (17,34): error CS0103: The name 'x5' does not exist in the current context // System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(17, 34), // (21,12): error CS0103: The name 'x5' does not exist in the current context // : base(x5) Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(21, 12), // (22,33): error CS0103: The name 'x5' does not exist in the current context // => System.Console.WriteLine(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(22, 33), // (27,34): error CS0103: The name 'x6' does not exist in the current context // System.Console.WriteLine(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(27, 34) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(4, x5Ref.Length); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); VerifyNotInScope(model, x5Ref[3]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,45): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IFieldInitializerOperation (Field: System.Boolean X.Test1) (OperationKind.FieldInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = TakeOutParam(1, out int x1) && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void FieldInitializers_05() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,54): error CS0165: Use of unassigned local variable 'x1' // bool Test1 = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void FieldInitializers_06() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static int Test1 = TakeOutParam(1, out var x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void Scope_Fixed_01() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { fixed (int* p = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p = Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p = Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // fixed (int* p = Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { fixed (int* p = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2 = Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p = Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Fixed_02() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* x1 = Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { fixed (int* p = Dummy(TakeOutParam(true, out var x2) && x2), x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p = Dummy(TakeOutParam(true, out var x3) && x3)) { Dummy(x3); } } void Test4() { fixed (int* p1 = Dummy(TakeOutParam(true, out var x4) && x4), p2 = Dummy(TakeOutParam(true, out var x4) && x4)) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (14,66): error CS0165: Use of unassigned local variable 'x1' // Dummy(TakeOutParam(true, out var x1) && x1)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 66), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p = Dummy(TakeOutParam(true, out var x3) && x3)) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2 = Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out var x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Fixed_02() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(TakeOutParam(""fixed"", out string x1), x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } static bool TakeOutParam(string y, out string x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Scope_For_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for ( Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (; Dummy(TakeOutParam(true, out var x1) && x1) ;) { Dummy(x1); } } void Test2() { for (; Dummy(TakeOutParam(true, out var x2) && x2) ;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (; Dummy(TakeOutParam(true, out var x4) && x4) ;) Dummy(x4); } void Test6() { for (; Dummy(x6 && TakeOutParam(true, out var x6)) ;) Dummy(x6); } void Test7() { for (; Dummy(TakeOutParam(true, out var x7) && x7) ;) { var x7 = 12; Dummy(x7); } } void Test8() { for (; Dummy(TakeOutParam(true, out var x8) && x8) ;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (; Dummy(TakeOutParam(true, out var x9) && x9) ;) { Dummy(x9); for (; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;) Dummy(x9); } } void Test10() { for (; Dummy(TakeOutParam(y10, out var x10)) ;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (; // Dummy(TakeOutParam(y11, out var x11)) // ;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (; Dummy(TakeOutParam(y12, out var x12)) ;) var y12 = 12; } //void Test13() //{ // for (; // Dummy(TakeOutParam(y13, out var x13)) // ;) // let y13 = 12; //} void Test14() { for (; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_03() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(TakeOutParam(true, out var x1) && x1) ) { Dummy(x1); } } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2) ) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (;; Dummy(TakeOutParam(true, out var x4) && x4) ) Dummy(x4); } void Test6() { for (;; Dummy(x6 && TakeOutParam(true, out var x6)) ) Dummy(x6); } void Test7() { for (;; Dummy(TakeOutParam(true, out var x7) && x7) ) { var x7 = 12; Dummy(x7); } } void Test8() { for (;; Dummy(TakeOutParam(true, out var x8) && x8) ) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (;; Dummy(TakeOutParam(true, out var x9) && x9) ) { Dummy(x9); for (;; Dummy(TakeOutParam(true, out var x9) && x9) // 2 ) Dummy(x9); } } void Test10() { for (;; Dummy(TakeOutParam(y10, out var x10)) ) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (;; // Dummy(TakeOutParam(y11, out var x11)) // ) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (;; Dummy(TakeOutParam(y12, out var x12)) ) var y12 = 12; } //void Test13() //{ // for (;; // Dummy(TakeOutParam(y13, out var x13)) // ) // let y13 = 12; //} void Test14() { for (;; Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (16,19): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(16, 19), // (25,19): error CS0103: The name 'x2' does not exist in the current context // Dummy(x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(25, 19), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (44,19): error CS0103: The name 'x6' does not exist in the current context // Dummy(x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(44, 19), // (63,19): error CS0103: The name 'x8' does not exist in the current context // Dummy(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(63, 19), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (74,19): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(74, 19), // (78,23): error CS0103: The name 'x9' does not exist in the current context // Dummy(x9); Diagnostic(ErrorCode.ERR_NameNotInContext, "x9").WithArguments("x9").WithLocation(78, 23), // (71,14): warning CS0162: Unreachable code detected // Dummy(TakeOutParam(true, out var x9) && x9) Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(71, 14), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44), // (128,19): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(128, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref[0]); VerifyNotInScope(model, x2Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref[0]); VerifyNotInScope(model, x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0]); VerifyNotInScope(model, x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyNotInScope(model, x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyNotInScope(model, x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref[0]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); VerifyNotInScope(model, x14Ref[1]); } [Fact] public void Scope_For_04() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (var b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (var b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (var b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (var b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (var b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (var b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (var b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (var b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (var b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (var b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (var b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (var b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_05() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool b = Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } } void Test2() { for (bool b = Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool b = Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); } void Test6() { for (bool b = Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); } void Test7() { for (bool b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool b = Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool b1 = Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for (bool b2 = Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } } void Test10() { for (bool b = Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool b = // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool b = Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; } //void Test13() //{ // for (bool b = // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; //} void Test14() { for (bool b = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_For_06() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (var x1 = Dummy(TakeOutParam(true, out var x1) && x1) ;;) {} } void Test2() { for (var x2 = true; Dummy(TakeOutParam(true, out var x2) && x2) ;) {} } void Test3() { for (var x3 = true;; Dummy(TakeOutParam(true, out var x3) && x3) ) {} } void Test4() { for (bool x4 = Dummy(TakeOutParam(true, out var x4) && x4) ;;) {} } void Test5() { for (bool x5 = true; Dummy(TakeOutParam(true, out var x5) && x5) ;) {} } void Test6() { for (bool x6 = true;; Dummy(TakeOutParam(true, out var x6) && x6) ) {} } void Test7() { for (bool x7 = true, b = Dummy(TakeOutParam(true, out var x7) && x7) ;;) {} } void Test8() { for (bool b1 = Dummy(TakeOutParam(true, out var x8) && x8), b2 = Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2 = Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } void Test10() { for (var b = x10; Dummy(TakeOutParam(true, out var x10) && x10) && Dummy(TakeOutParam(true, out var x10) && x10); Dummy(TakeOutParam(true, out var x10) && x10)) {} } void Test11() { for (bool b = x11; Dummy(TakeOutParam(true, out var x11) && x11) && Dummy(TakeOutParam(true, out var x11) && x11); Dummy(TakeOutParam(true, out var x11) && x11)) {} } void Test12() { for (Dummy(x12); Dummy(x12) && Dummy(TakeOutParam(true, out var x12) && x12); Dummy(TakeOutParam(true, out var x12) && x12)) {} } void Test13() { for (var b = x13; Dummy(x13); Dummy(TakeOutParam(true, out var x13) && x13), Dummy(TakeOutParam(true, out var x13) && x13)) {} } void Test14() { for (bool b = x14; Dummy(x14); Dummy(TakeOutParam(true, out var x14) && x14), Dummy(TakeOutParam(true, out var x14) && x14)) {} } void Test15() { for (Dummy(x15); Dummy(x15); Dummy(x15), Dummy(TakeOutParam(true, out var x15) && x15)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,47): error CS0128: A local variable or function named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 47), // (13,54): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1) && x1) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 54), // (21,47): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x2) && x2) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 47), // (20,18): warning CS0219: The variable 'x2' is assigned but its value is never used // for (var x2 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(20, 18), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x3) && x3) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (28,18): warning CS0219: The variable 'x3' is assigned but its value is never used // for (var x3 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x3").WithArguments("x3").WithLocation(28, 18), // (37,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(37, 47), // (37,54): error CS0165: Use of unassigned local variable 'x4' // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(37, 54), // (45,47): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x5) && x5) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(45, 47), // (44,19): warning CS0219: The variable 'x5' is assigned but its value is never used // for (bool x5 = true; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(44, 19), // (53,47): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x6) && x6) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(53, 47), // (52,19): warning CS0219: The variable 'x6' is assigned but its value is never used // for (bool x6 = true;; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(52, 19), // (61,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(61, 47), // (69,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2 = Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(69, 52), // (70,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(70, 47), // (71,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(71, 47), // (77,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(77, 23), // (79,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(79, 47), // (80,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(80, 47), // (86,22): error CS0103: The name 'x10' does not exist in the current context // for (var b = x10; Diagnostic(ErrorCode.ERR_NameNotInContext, "x10").WithArguments("x10").WithLocation(86, 22), // (88,47): error CS0128: A local variable or function named 'x10' is already defined in this scope // Dummy(TakeOutParam(true, out var x10) && x10); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x10").WithArguments("x10").WithLocation(88, 47), // (89,47): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x10) && x10)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(89, 47), // (95,23): error CS0103: The name 'x11' does not exist in the current context // for (bool b = x11; Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(95, 23), // (97,47): error CS0128: A local variable or function named 'x11' is already defined in this scope // Dummy(TakeOutParam(true, out var x11) && x11); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x11").WithArguments("x11").WithLocation(97, 47), // (98,47): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x11) && x11)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(98, 47), // (104,20): error CS0103: The name 'x12' does not exist in the current context // for (Dummy(x12); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(104, 20), // (105,20): error CS0841: Cannot use local variable 'x12' before it is declared // Dummy(x12) && Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(105, 20), // (107,47): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x12) && x12)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(107, 47), // (113,22): error CS0103: The name 'x13' does not exist in the current context // for (var b = x13; Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(113, 22), // (114,20): error CS0103: The name 'x13' does not exist in the current context // Dummy(x13); Diagnostic(ErrorCode.ERR_NameNotInContext, "x13").WithArguments("x13").WithLocation(114, 20), // (116,47): error CS0128: A local variable or function named 'x13' is already defined in this scope // Dummy(TakeOutParam(true, out var x13) && x13)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x13").WithArguments("x13").WithLocation(116, 47), // (122,23): error CS0103: The name 'x14' does not exist in the current context // for (bool b = x14; Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(122, 23), // (123,20): error CS0103: The name 'x14' does not exist in the current context // Dummy(x14); Diagnostic(ErrorCode.ERR_NameNotInContext, "x14").WithArguments("x14").WithLocation(123, 20), // (125,47): error CS0128: A local variable or function named 'x14' is already defined in this scope // Dummy(TakeOutParam(true, out var x14) && x14)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(125, 47), // (131,20): error CS0103: The name 'x15' does not exist in the current context // for (Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(131, 20), // (132,20): error CS0103: The name 'x15' does not exist in the current context // Dummy(x15); Diagnostic(ErrorCode.ERR_NameNotInContext, "x15").WithArguments("x15").WithLocation(132, 20), // (133,20): error CS0841: Cannot use local variable 'x15' before it is declared // Dummy(x15), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x15").WithArguments("x15").WithLocation(133, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(3, x10Decl.Length); Assert.Equal(4, x10Ref.Length); VerifyNotInScope(model, x10Ref[0]); VerifyModelForOutVar(model, x10Decl[0], x10Ref[1], x10Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x10Decl[1]); VerifyModelForOutVar(model, x10Decl[2], x10Ref[3]); var x11Decl = GetOutVarDeclarations(tree, "x11").ToArray(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Decl.Length); Assert.Equal(4, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl[0], x11Ref[1], x11Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x11Decl[1]); VerifyModelForOutVar(model, x11Decl[2], x11Ref[3]); var x12Decl = GetOutVarDeclarations(tree, "x12").ToArray(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Decl.Length); Assert.Equal(4, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl[0], x12Ref[1], x12Ref[2]); VerifyModelForOutVar(model, x12Decl[1], x12Ref[3]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(4, x13Ref.Length); VerifyNotInScope(model, x13Ref[0]); VerifyNotInScope(model, x13Ref[1]); VerifyModelForOutVar(model, x13Decl[0], x13Ref[2], x13Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x13Decl[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyNotInScope(model, x14Ref[0]); VerifyNotInScope(model, x14Ref[1]); VerifyModelForOutVar(model, x14Decl[0], x14Ref[2], x14Ref[3]); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(4, x15Ref.Length); VerifyNotInScope(model, x15Ref[0]); VerifyNotInScope(model, x15Ref[1]); VerifyModelForOutVar(model, x15Decl, x15Ref[2], x15Ref[3]); } [Fact] public void Scope_For_07() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (;; Dummy(x1), Dummy(TakeOutParam(true, out var x1) && x1)) {} } void Test2() { for (;; Dummy(TakeOutParam(true, out var x2) && x2), Dummy(TakeOutParam(true, out var x2) && x2)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,20): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(x1), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 20), // (22,47): error CS0128: A local variable or function named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2) && x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); f = false, Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (TakeOutParam(1, out var x0); Dummy(x0 < 3, TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForOutVar(model, x0Decl[0], x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_06() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1))) { x0++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"20 30 -- 20 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void For_07() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (int x0 = 1; x0 < 3; Dummy(TakeOutParam(x0*10, out var x1), x1, l, () => System.Console.WriteLine(""{0}"", x1)), x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static void Dummy(object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 -- 10 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Foreach_01() { var source = @" public class X { public static void Main() { } System.Collections.IEnumerable Dummy(params object[] x) {return null;} void Test1() { foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); } void Test6() { foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } void Test15() { foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } } static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,60): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 60), // (35,33): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 33), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,65): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 65), // (68,46): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 46), // (86,46): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 46), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,57): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 57), // (108,22): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(108, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_If_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (TakeOutParam(true, out var x1)) { Dummy(x1); } else { System.Console.WriteLine(x1); } } void Test2() { if (TakeOutParam(true, out var x2)) Dummy(x2); else System.Console.WriteLine(x2); } void Test3() { if (TakeOutParam(true, out var x3)) Dummy(x3); else { var x3 = 12; System.Console.WriteLine(x3); } } void Test4() { var x4 = 11; Dummy(x4); if (TakeOutParam(true, out var x4)) Dummy(x4); } void Test5(int x5) { if (TakeOutParam(true, out var x5)) Dummy(x5); } void Test6() { if (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { if (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { if (TakeOutParam(true, out var x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { if (TakeOutParam(true, out var x9)) { Dummy(x9); if (TakeOutParam(true, out var x9)) // 2 Dummy(x9); } } void Test10() { if (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } void Test12() { if (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // if (TakeOutParam(y13, out var x13)) // let y13 = 12; //} static bool TakeOutParam(int y, out int x) { x = y; return true; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (101,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(101, 13), // (36,17): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x3 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(36, 17), // (46,40): error CS0128: A local variable named 'x4' is already defined in this scope // if (TakeOutParam(true, out var x4)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(46, 40), // (52,40): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x5)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(52, 40), // (58,13): error CS0841: Cannot use local variable 'x6' before it is declared // if (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(58, 13), // (66,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(66, 17), // (83,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(83, 19), // (84,44): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // if (TakeOutParam(true, out var x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(84, 44), // (91,26): error CS0103: The name 'y10' does not exist in the current context // if (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(91, 26), // (100,26): error CS0103: The name 'y12' does not exist in the current context // if (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(100, 26), // (101,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(101, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); } [Fact] public void Scope_If_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) if (TakeOutParam(true, out var x1)) { } else { } x1++; } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_If_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (IfStatementSyntax)SyntaxFactory.ParseStatement(@" if (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, TakeOutParam(val, out var x1), x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) ; if (f) { if (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_Lambda_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} System.Action<object> Test1() { return (o) => let x1 = o; } System.Action<object> Test2() { return (o) => let var x2 = o; } void Test3() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x3) && x3 > 0)); } void Test4() { Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); } void Test5() { Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out int x5) && TakeOutParam(o2, out int x5) && x5 > 0)); } void Test6() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out int x6) && x6 > 0)); } void Test7() { Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out int x7) && x7 > 0), x7); Dummy(x7, 2); } void Test8() { Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out int y8) && x8)); } void Test9() { Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && x9 > 0), x9); } void Test10() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && x10 > 0), TakeOutParam(true, out var x10), x10); } void Test11() { var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && x11 > 0), x11); } void Test12() { Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (12,27): error CS1002: ; expected // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "x1").WithLocation(12, 27), // (17,27): error CS1002: ; expected // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_SemicolonExpected, "var").WithLocation(17, 27), // (12,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(12, 23), // (12,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(12, 23), // (12,27): error CS0103: The name 'x1' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(12, 27), // (12,32): error CS0103: The name 'o' does not exist in the current context // return (o) => let x1 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(12, 32), // (12,27): warning CS0162: Unreachable code detected // return (o) => let x1 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "x1").WithLocation(12, 27), // (17,23): error CS0103: The name 'let' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "let").WithArguments("let").WithLocation(17, 23), // (17,23): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_IllegalStatement, "let").WithLocation(17, 23), // (17,36): error CS0103: The name 'o' does not exist in the current context // return (o) => let var x2 = o; Diagnostic(ErrorCode.ERR_NameNotInContext, "o").WithArguments("o").WithLocation(17, 36), // (17,27): warning CS0162: Unreachable code detected // return (o) => let var x2 = o; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(17, 27), // (27,49): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out int x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(27, 49), // (33,89): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(o2, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(33, 89), // (44,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(44, 15), // (45,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(45, 15), // (47,15): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(47, 15), // (48,15): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(48, 15), // (59,73): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // (System.Func<object, bool>) (o => TakeOutParam(o, out int x9) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(59, 73), // (65,73): error CS0136: A local or parameter named 'x10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x10) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x10").WithArguments("x10").WithLocation(65, 73), // (74,73): error CS0136: A local or parameter named 'x11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x11) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x11").WithArguments("x11").WithLocation(74, 73), // (80,73): error CS0136: A local or parameter named 'x12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out int x12) && Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x12").WithArguments("x12").WithLocation(80, 73), // (82,15): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(82, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Scope_LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { var d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { var d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // var d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // var d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); object d = Dummy(TakeOutParam(true, out var x4), x4); } void Test6() { object d = Dummy(x6 && TakeOutParam(true, out var x6)); } void Test8() { object d = Dummy(TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { object d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,53): error CS0128: A local variable named 'x4' is already defined in this scope // object d = Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 53), // (24,26): error CS0841: Cannot use local variable 'x6' before it is declared // object d = Dummy(x6 && TakeOutParam(true, out var x6)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 26), // (36,50): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_LocalDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var x1 = Dummy(TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { object x2 = Dummy(TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] public void Scope_LocalDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Scope_LocalDeclarationStmt_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y1 = Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Int64 y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] public void Scope_LocalDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d =TakeOutParam(true, out var x1) && x1 != null; x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d =TakeOutParam(true, out var x1) && x1 != null;").WithLocation(11, 13), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (d, dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); var (d, dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { var (d, dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { var (d, dd, ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,51): error CS0128: A local variable named 'x4' is already defined in this scope // var (d, dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 51), // (24,24): error CS0841: Cannot use local variable 'x6' before it is declared // var (d, dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 24), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object dd) = (TakeOutParam(true, out var x1), x1); } void Test4() { var x4 = 11; Dummy(x4); (object d, object dd) = (TakeOutParam(true, out var x4), x4); } void Test6() { (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); } void Test8() { (object d, object dd) = (TakeOutParam(true, out var x8), x8); System.Console.WriteLine(x8); } void Test14() { (object d, object dd, object ddd) = (TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,61): error CS0128: A local variable named 'x4' is already defined in this scope // (object d, object dd) = (TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 61), // (24,34): error CS0841: Cannot use local variable 'x6' before it is declared // (object d, object dd) = (x6 && TakeOutParam(true, out var x6), 1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var (x1, dd) = (TakeOutParam(true, out var x1), x1); Dummy(x1); } void Test2() { (object x2, object dd) = (TakeOutParam(true, out var x2), x2); Dummy(x2); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (13,56): error CS0841: Cannot use local variable 'x1' before it is declared // (TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(13, 56), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // (TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Dummy(x1)); Dummy(x1); } void Test2() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x2), x2), Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { (object d1, object d2) = (Dummy(TakeOutParam(true, out var x3), x3), Dummy(x3)); } void Test4() { (object d1, object d2) = (Dummy(x4), Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,67): error CS0128: A local variable named 'x1' is already defined in this scope // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 67), // (12,72): error CS0165: Use of unassigned local variable 'x1' // (object d, object x1) = (Dummy(TakeOutParam(true, out var x1), x1), Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(12, 72), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,41): error CS0841: Cannot use local variable 'x4' before it is declared // (object d1, object d2) = (Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyNotAnOutLocal(model, x1Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_05() { var source = @" public class X { public static void Main() { } void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ExpressionStatementSyntax)SyntaxFactory.ParseStatement(@" var (y1, dd) = (TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); Assert.Equal("System.Boolean y1", model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single().ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_DeconstructionDeclarationStmt_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var (d, dd) = (TakeOutParam(true, out var x1), x1); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var d = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(id => id.Identifier.ValueText == "d").Single(); Assert.Equal("System.Boolean d", model.GetDeclaredSymbol(d).ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1), x1), (Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2), x2), Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl[0], x3Ref); } [Fact] public void Scope_Lock_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { lock (Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } } void Test2() { lock (Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Dummy(x4); } void Test6() { lock (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { lock (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { lock (Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { lock (Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } } void Test10() { lock (Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // lock (Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { lock (Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; } //void Test13() //{ // lock (Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; //} void Test14() { lock (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam(bool y, out bool x) { x = y; return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,48): error CS0128: A local variable named 'x4' is already defined in this scope // lock (Dummy(TakeOutParam(true, out var x4) && x4 > 0)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(29, 48), // (35,21): error CS0841: Cannot use local variable 'x6' before it is declared // lock (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 21), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (60,19): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(60, 19), // (61,52): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // lock (Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 52), // (68,34): error CS0103: The name 'y10' does not exist in the current context // lock (Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 34), // (86,34): error CS0103: The name 'y12' does not exist in the current context // lock (Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 34), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,45): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 45) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Lock_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { if (true) lock (Dummy(TakeOutParam(true, out var x1))) { } x1++; } static object TakeOutParam(bool y, out bool x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (17,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(17, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Lock_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LockStatementSyntax)SyntaxFactory.ParseStatement(@" lock (Dummy(TakeOutParam(true, out var x1), x1)) ; "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(TakeOutParam(""lock"", out var x1), x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { lock (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void Scope_ParameterDefault_01() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out int x4)) {} void Test5(bool p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out int x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out int x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out int x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out int x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out int x6) && x6 > 0, bool p2 = TakeOutParam(6, out int x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out int x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out int x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out int x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IParameterInitializerOperation (Parameter: [System.Boolean p = default(System.Boolean)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= TakeOutPa ... ) && x3 > 0') Locals: Local_1: System.Int32 x3 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... ) && x3 > 0') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean, IsInvalid) (Syntax: 'TakeOutPara ... out int x3)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out int x3') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3') ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'x3 > 0') Left: ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') "); } [Fact] public void Scope_ParameterDefault_02() { var source = @" public class X { public static void Main() { } void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) {} void Test4(bool p = x4 && TakeOutParam(4, out var x4)) {} void Test5(bool p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0) {} void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) {} void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) { } void Test72(bool p = x7 > 2) {} void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test3(bool p = TakeOutParam(3, out var x3) && x3 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(3, out var x3) && x3 > 0").WithArguments("p").WithLocation(8, 25), // (11,25): error CS0841: Cannot use local variable 'x4' before it is declared // void Test4(bool p = x4 && TakeOutParam(4, out var x4)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(11, 25), // (15,50): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 50), // (14,25): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test5(bool p = TakeOutParam(51, out var x5) && Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @"TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0").WithArguments("p").WithLocation(14, 25), // (19,27): error CS1736: Default parameter value for 'p1' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p1").WithLocation(19, 27), // (19,76): error CS1736: Default parameter value for 'p2' must be a compile-time constant // void Test61(bool p1 = TakeOutParam(6, out var x6) && x6 > 0, bool p2 = TakeOutParam(6, out var x6) && x6 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(6, out var x6) && x6 > 0").WithArguments("p2").WithLocation(19, 76), // (22,26): error CS1736: Default parameter value for 'p' must be a compile-time constant // void Test71(bool p = TakeOutParam(7, out var x7) && x7 > 0) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "TakeOutParam(7, out var x7) && x7 > 0").WithArguments("p").WithLocation(22, 26), // (26,26): error CS0103: The name 'x7' does not exist in the current context // void Test72(bool p = x7 > 2) Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(26, 26), // (29,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(29, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_PropertyInitializers_01() { var source = @" public class X { public static void Main() { } bool Test3 {get;} = TakeOutParam(3, out int x3) && x3 > 0; bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); bool Test5 {get;} = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0; bool Test61 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test62 {get;} = TakeOutParam(6, out int x6) && x6 > 0; bool Test71 {get;} = TakeOutParam(7, out int x7) && x7 > 0; bool Test72 {get;} = Dummy(x7, 2); void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,25): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 {get;} = x4 && TakeOutParam(4, out int x4); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 25), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (19,32): error CS0103: The name 'x7' does not exist in the current context // bool Test72 {get;} = Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(19, 32), // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = TakeOutParam(1, out int x1) && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 52) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); compilation.VerifyOperationTree(node, expectedOperationTree: @" IPropertyInitializerOperation (Property: System.Boolean X.Test1 { get; }) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= TakeOutPa ... & Dummy(x1)') Locals: Local_1: System.Int32 x1 IBinaryOperation (BinaryOperatorKind.ConditionalAnd) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'TakeOutPara ... & Dummy(x1)') Left: IInvocationOperation (System.Boolean X.TakeOutParam(System.Int32 y, out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'TakeOutPara ... out int x1)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IInvocationOperation (System.Boolean X.Dummy(System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Dummy(x1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x1') ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => TakeOutParam(1, out int x1) && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_03() { var source = @" public class X { public static void Main() { } static bool a = false; bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,63): error CS0165: Use of unassigned local variable 'x1' // bool Test1 { get; } = a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(8, 63) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void PropertyInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(new X().Test1); } int Test1 { get; } = TakeOutParam(1, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Scope_Query_01() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); } void Test2() { var res = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); } void Test3() { var res = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); } void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } void Test6() { var res = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); } void Test7() { var res = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); } void Test8() { var res = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); } void Test9() { var res = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); } void Test10() { var res = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; } void Test11() { var res = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (25,26): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(25, 26), // (27,15): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(27, 15), // (35,32): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(35, 32), // (37,15): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(37, 15), // (45,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(45, 35), // (47,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(47, 35), // (49,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(49, 32), // (49,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(49, 36), // (52,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(52, 15), // (53,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(53, 15), // (61,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(61, 35), // (63,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(63, 35), // (66,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(66, 32), // (66,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(66, 36), // (69,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(69, 15), // (70,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(70, 15), // (78,26): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(78, 26), // (80,15): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(80, 15), // (87,27): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(87, 27), // (89,27): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(89, 27), // (91,26): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(91, 26), // (91,31): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(91, 31), // (93,15): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(93, 15), // (94,15): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(94, 15), // (102,15): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(102, 15), // (112,25): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(112, 25), // (109,25): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(109, 25), // (114,15): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(114, 15), // (115,15): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(115, 15), // (121,24): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(121, 24), // (128,23): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(128, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } [Fact] public void Scope_Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { var res = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); } void Test5() { var res = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} select x1 into x1 join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4 , out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,35): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(18, 35), // (20,35): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(20, 35), // (22,32): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(22, 32), // (22,36): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(22, 36), // (25,15): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(25, 15), // (26,15): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(26, 15), // (35,35): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(35, 35), // (37,35): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(37, 35), // (40,32): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(40, 32), // (40,36): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(40, 36), // (43,15): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(43, 15), // (44,15): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(44, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { int y1 = 0, y2 = 0, y3 = 0, y4 = 0, y5 = 0, y6 = 0, y7 = 0, y8 = 0, y9 = 0, y10 = 0, y11 = 0, y12 = 0; var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12 + (TakeOutParam(13, out var y13) ? y13 : 0); Dummy(y1, y2, y3, y4, y5, y6, y7, y8, y9, y10, y11, y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (16,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // var res = from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(16, 62), // (17,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(17, 62), // (18,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62), // (19,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(19, 51), // (20,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(20, 58), // (21,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(21, 49), // (22,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(22, 51), // (23,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(23, 51), // (25,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(25, 47), // (24,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(24, 49), // (27,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(27, 54), // (28,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(28, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(3, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVarDuplicateInSameScope(model, yDecl); VerifyNotAnOutLocal(model, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); break; } VerifyNotAnOutLocal(model, yRef[2]); switch (i) { case 12: VerifyNotAnOutLocal(model, yRef[1]); break; default: VerifyNotAnOutLocal(model, yRef[1]); break; } } var y13Decl = GetOutVarDeclarations(tree, "y13").Single(); var y13Ref = GetReference(tree, "y13"); VerifyModelForOutVar(model, y13Decl, y13Ref); } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_06() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y1), TakeOutParam(out int y2), TakeOutParam(out int y3), TakeOutParam(out int y4), TakeOutParam(out int y5), TakeOutParam(out int y6), TakeOutParam(out int y7), TakeOutParam(out int y8), TakeOutParam(out int y9), TakeOutParam(out int y10), TakeOutParam(out int y11), TakeOutParam(out int y12), from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on TakeOutParam(4, out var y4) ? y4 : 0 equals TakeOutParam(5, out var y5) ? y5 : 0 where TakeOutParam(6, out var y6) && y6 == 1 orderby TakeOutParam(7, out var y7) && y7 > 0, TakeOutParam(8, out var y8) && y8 > 0 group TakeOutParam(9, out var y9) && y9 > 0 by TakeOutParam(10, out var y10) && y10 > 0 into g let x11 = TakeOutParam(11, out var y11) && y11 > 0 select TakeOutParam(12, out var y12) && y12 > 0 into s select y1 + y2 + y3 + y4 + y5 + y6 + y7 + y8 + y9 + y10 + y11 + y12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (26,62): error CS0128: A local variable or function named 'y1' is already defined in this scope // from x1 in new[] { TakeOutParam(1, out var y1) ? y1 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y1").WithArguments("y1").WithLocation(26, 62), // (27,62): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(2, out var y2) ? y2 : 0} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(27, 62), // (28,62): error CS0128: A local variable or function named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(28, 62), // (29,51): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(4, out var y4) ? y4 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(29, 51), // (30,58): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(5, out var y5) ? y5 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(30, 58), // (31,49): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(6, out var y6) && y6 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(31, 49), // (32,51): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(7, out var y7) && y7 > 0, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(32, 51), // (33,51): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(8, out var y8) && y8 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(33, 51), // (35,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(10, out var y10) && y10 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(35, 47), // (34,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(9, out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(34, 49), // (37,54): error CS0136: A local or parameter named 'y11' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x11 = TakeOutParam(11, out var y11) && y11 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y11").WithArguments("y11").WithLocation(37, 54), // (38,51): error CS0136: A local or parameter named 'y12' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(12, out var y12) && y12 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y12").WithArguments("y12").WithLocation(38, 51) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); switch (i) { case 1: case 3: VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); break; case 12: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; default: VerifyModelForOutVar(model, yDecl[0], yRef[1]); VerifyModelForOutVar(model, yDecl[1], yRef[0]); break; } } } [Fact] public void Scope_Query_07() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { Dummy(TakeOutParam(out int y3), from x1 in new[] { 0 } select x1 into x1 join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} on x1 equals x3 select y3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,62): error CS0128: A local variable named 'y3' is already defined in this scope // join x3 in new[] { TakeOutParam(3, out var y3) ? y3 : 0} Diagnostic(ErrorCode.ERR_LocalDuplicate, "y3").WithArguments("y3").WithLocation(18, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); const string id = "y3"; var yDecl = GetOutVarDeclarations(tree, id).ToArray(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(2, yDecl.Length); Assert.Equal(2, yRef.Length); // Since the name is declared twice in the same scope, // both references are to the same declaration. VerifyModelForOutVar(model, yDecl[0], yRef); VerifyModelForOutVarDuplicateInSameScope(model, yDecl[1]); } [Fact] public void Scope_Query_08() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4) ) ? 1 : 0} from y1 in new[] { 1 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by x1 into y4 select y4; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // from y1 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(19, 24), // (20,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(20, 24), // (22,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(22, 23), // (25,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(25, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 5; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] public void Scope_Query_09() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } join y2 in new[] { 0 } on y1 equals y2 let y3 = 0 group y3 by 1 into y4 select y4 == null ? 1 : 0 into x2 join y5 in new[] { Dummy(TakeOutParam(out var y1), TakeOutParam(out var y2), TakeOutParam(out var y3), TakeOutParam(out var y4), TakeOutParam(out var y5) ) ? 1 : 0 } on x2 equals y5 select x2; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,24): error CS1931: The range variable 'y1' conflicts with a previous declaration of 'y1' // var res = from y1 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y1").WithArguments("y1").WithLocation(14, 24), // (15,24): error CS1931: The range variable 'y2' conflicts with a previous declaration of 'y2' // join y2 in new[] { 0 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y2").WithArguments("y2").WithLocation(15, 24), // (17,23): error CS1931: The range variable 'y3' conflicts with a previous declaration of 'y3' // let y3 = 0 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y3").WithArguments("y3").WithLocation(17, 23), // (20,24): error CS1931: The range variable 'y4' conflicts with a previous declaration of 'y4' // into y4 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y4").WithArguments("y4").WithLocation(20, 24), // (23,24): error CS1931: The range variable 'y5' conflicts with a previous declaration of 'y5' // join y5 in new[] { Dummy(TakeOutParam(out var y1), Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y5").WithArguments("y5").WithLocation(23, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 6; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); switch (i) { case 4: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; case 5: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; default: VerifyModelForOutVar(model, yDecl); VerifyNotAnOutLocal(model, yRef); break; } } } [Fact] [WorkItem(10466, "https://github.com/dotnet/roslyn/issues/10466")] [WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")] public void Scope_Query_10() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from y1 in new[] { 0 } from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } select y1; } void Test2() { var res = from y2 in new[] { 0 } join x3 in new[] { 1 } on TakeOutParam(out var y2) ? y2 : 0 equals x3 select y2; } void Test3() { var res = from x3 in new[] { 0 } join y3 in new[] { 1 } on x3 equals TakeOutParam(out var y3) ? y3 : 0 select y3; } void Test4() { var res = from y4 in new[] { 0 } where TakeOutParam(out var y4) && y4 == 1 select y4; } void Test5() { var res = from y5 in new[] { 0 } orderby TakeOutParam(out var y5) && y5 > 1, 1 select y5; } void Test6() { var res = from y6 in new[] { 0 } orderby 1, TakeOutParam(out var y6) && y6 > 1 select y6; } void Test7() { var res = from y7 in new[] { 0 } group TakeOutParam(out var y7) && y7 == 3 by y7; } void Test8() { var res = from y8 in new[] { 0 } group y8 by TakeOutParam(out var y8) && y8 == 3; } void Test9() { var res = from y9 in new[] { 0 } let x4 = TakeOutParam(out var y9) && y9 > 0 select y9; } void Test10() { var res = from y10 in new[] { 0 } select TakeOutParam(out var y10) && y10 > 0; } static bool TakeOutParam(out int x) { x = 0; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // error CS0412 is misleading and reported due to preexisting bug https://github.com/dotnet/roslyn/issues/12052 compilation.VerifyDiagnostics( // (15,59): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // from x2 in new[] { TakeOutParam(out var y1) ? y1 : 1 } Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(15, 59), // (23,48): error CS0136: A local or parameter named 'y2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // on TakeOutParam(out var y2) ? y2 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y2").WithArguments("y2").WithLocation(23, 48), // (33,52): error CS0136: A local or parameter named 'y3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // equals TakeOutParam(out var y3) ? y3 : 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y3").WithArguments("y3").WithLocation(33, 52), // (40,46): error CS0136: A local or parameter named 'y4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(out var y4) && y4 == 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y4").WithArguments("y4").WithLocation(40, 46), // (47,48): error CS0136: A local or parameter named 'y5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // orderby TakeOutParam(out var y5) && y5 > 1, Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y5").WithArguments("y5").WithLocation(47, 48), // (56,48): error CS0136: A local or parameter named 'y6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // TakeOutParam(out var y6) && y6 > 1 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y6").WithArguments("y6").WithLocation(56, 48), // (63,46): error CS0136: A local or parameter named 'y7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // group TakeOutParam(out var y7) && y7 == 3 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y7").WithArguments("y7").WithLocation(63, 46), // (71,43): error CS0136: A local or parameter named 'y8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // by TakeOutParam(out var y8) && y8 == 3; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y8").WithArguments("y8").WithLocation(71, 43), // (77,49): error CS0136: A local or parameter named 'y9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // let x4 = TakeOutParam(out var y9) && y9 > 0 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y9").WithArguments("y9").WithLocation(77, 49), // (84,47): error CS0136: A local or parameter named 'y10' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // select TakeOutParam(out var y10) && y10 > 0; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y10").WithArguments("y10").WithLocation(84, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 11; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).ToArray(); Assert.Equal(i == 10 ? 1 : 2, yRef.Length); switch (i) { case 4: case 6: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; case 8: VerifyModelForOutVar(model, yDecl, yRef[1]); VerifyNotAnOutLocal(model, yRef[0]); break; case 10: VerifyModelForOutVar(model, yDecl, yRef[0]); break; default: VerifyModelForOutVar(model, yDecl, yRef[0]); VerifyNotAnOutLocal(model, yRef[1]); break; } } } [Fact] public void Scope_Query_11() { var source = @" using System.Linq; public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y1), from x2 in new [] { y1 } where TakeOutParam(x1, out var y1) select x2) select x1; } void Test2() { var res = from x1 in new [] { 1 } where Dummy(TakeOutParam(x1, out var y2), TakeOutParam(x1 + 1, out var y2)) select x1; } void Test3() { var res = from x1 in new [] { 1 } where TakeOutParam(out int y3, y3) select x1; } void Test4() { var res = from x1 in new [] { 1 } where TakeOutParam(out var y4, y4) select x1; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool TakeOutParam(out int x, int y) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_3); compilation.VerifyDiagnostics( // (17,62): error CS0136: A local or parameter named 'y1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // where TakeOutParam(x1, out var y1) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y1").WithArguments("y1").WithLocation(17, 62), // (26,60): error CS0128: A local variable or function named 'y2' is already defined in this scope // TakeOutParam(x1 + 1, out var y2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "y2").WithArguments("y2").WithLocation(26, 60), // (33,50): error CS0165: Use of unassigned local variable 'y3' // where TakeOutParam(out int y3, y3) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(33, 50), // (40,50): error CS8196: Reference to an implicitly-typed out variable 'y4' is not permitted in the same argument list. // where TakeOutParam(out var y4, y4) Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "y4").WithArguments("y4").WithLocation(40, 50) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").ToArray(); var y1Ref = GetReferences(tree, "y1").Single(); Assert.Equal(2, y1Decl.Length); VerifyModelForOutVar(model, y1Decl[0], y1Ref); VerifyModelForOutVar(model, y1Decl[1]); var y2Decl = GetOutVarDeclarations(tree, "y2").ToArray(); Assert.Equal(2, y2Decl.Length); VerifyModelForOutVar(model, y2Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, y2Decl[1]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").Single(); VerifyModelForOutVarWithoutDataFlow(model, y3Decl, y3Ref); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").Single(); VerifyModelForOutVarWithoutDataFlow(model, y4Decl, y4Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 1 : 0} from x2 in new[] { TakeOutParam(2, out var y2) && Print(y2) ? 1 : 0} join x3 in new[] { TakeOutParam(3, out var y3) && Print(y3) ? 1 : 0} on TakeOutParam(4, out var y4) && Print(y4) ? 1 : 0 equals TakeOutParam(5, out var y5) && Print(y5) ? 1 : 0 where TakeOutParam(6, out var y6) && Print(y6) orderby TakeOutParam(7, out var y7) && Print(y7), TakeOutParam(8, out var y8) && Print(y8) group TakeOutParam(9, out var y9) && Print(y9) by TakeOutParam(10, out var y10) && Print(y10) into g let x11 = TakeOutParam(11, out var y11) && Print(y11) select TakeOutParam(12, out var y12) && Print(y12); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetOutVarDeclarations(tree, id).Single(); var yRef = GetReferences(tree, id).Single(); VerifyModelForOutVar(model, yDecl, yRef); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(yDecl))).Type.ToTestDisplayString()); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutVar(model, yDecl, yRef); } [Fact] public void Query_03() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in new[] { true } select a && TakeOutParam(3, out int x1) || x1 > 0; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,62): error CS0165: Use of unassigned local variable 'x1' // select a && TakeOutParam(3, out int x1) || x1 > 0; Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 62) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); compilation.VerifyOperationTree(x1Decl, expectedOperationTree: @" IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1') "); } [Fact] public void Query_04() { var source = @" using System.Linq; public class X { public static void Main() { System.Console.WriteLine(Test1()); } static int Test1() { var res = from a in new[] { 1 } select TakeOutParam(a, out int x1) ? Test2(((System.Func<int>)(() => x1++))(), ref x1) : -1; return res.Single(); } static int Test2(object a, ref int x) { System.Console.WriteLine(x); x++; return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void Query_05() { var source = @" using System.Linq; public class X { public static void Main() { } static void Test1() { var res = from a in (new[] { 1 }).AsQueryable() select TakeOutParam(a, out int x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,46): error CS8198: An expression tree may not contain an out argument variable declaration. // select TakeOutParam(a, out int x1); Diagnostic(ErrorCode.ERR_ExpressionTreeContainsOutVariable, "int x1").WithLocation(13, 46) ); } [Fact] public void Scope_ReturnStatement_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) { return null; } object Test1() { return Dummy(TakeOutParam(true, out var x1), x1); { return Dummy(TakeOutParam(true, out var x1), x1); } return Dummy(TakeOutParam(true, out var x1), x1); } object Test2() { return Dummy(x2, TakeOutParam(true, out var x2)); } object Test3(int x3) { return Dummy(TakeOutParam(true, out var x3), x3); } object Test4() { var x4 = 11; Dummy(x4); return Dummy(TakeOutParam(true, out var x4), x4); } object Test5() { return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //object Test6() //{ // let x6 = 11; // Dummy(x6); // return Dummy(TakeOutParam(true, out var x6), x6); //} //object Test7() //{ // return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} object Test8() { return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } object Test9(bool y9) { if (y9) return Dummy(TakeOutParam(true, out var x9), x9); return null; } System.Func<object> Test10(bool y10) { return () => { if (y10) return Dummy(TakeOutParam(true, out var x10), x10); return null;}; } object Test11() { Dummy(x11); return Dummy(TakeOutParam(true, out var x11), x11); } object Test12() { return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,53): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 53), // (16,49): error CS0128: A local variable or function named 'x1' is already defined in this scope // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 49), // (14,13): warning CS0162: Unreachable code detected // return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(14, 13), // (21,22): error CS0841: Cannot use local variable 'x2' before it is declared // return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 22), // (26,49): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 49), // (33,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 49), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,86): error CS0128: A local variable or function named 'x8' is already defined in this scope // return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 86), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ReturnStatement_02() { var source = @" public class X { public static void Main() { } int Dummy(params object[] x) { return 0;} int Test1(bool val) { if (val) return Dummy(TakeOutParam(true, out var x1)); x1++; return 0; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ReturnStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ReturnStatementSyntax)SyntaxFactory.ParseStatement(@" return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(TakeOutParam(""return"", out var x1), x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static object Test(bool val) { if (val) return Dummy(TakeOutParam(""return 1"", out var x2), x2); if (!val) { return Dummy(TakeOutParam(""return 2"", out var x2), x2); } return null; } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"return 1 return 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Switch_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { switch (TakeOutParam(1, out var x1) ? x1 : 0) { case 0: Dummy(x1, 0); break; } Dummy(x1, 1); } void Test4() { var x4 = 11; Dummy(x4); switch (TakeOutParam(4, out var x4) ? x4 : 0) { case 4: Dummy(x4); break; } } void Test5(int x5) { switch (TakeOutParam(5, out var x5) ? x5 : 0) { case 5: Dummy(x5); break; } } void Test6() { switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) { case 6: Dummy(x6); break; } } void Test7() { switch (TakeOutParam(7, out var x7) ? x7 : 0) { case 7: var x7 = 12; Dummy(x7); break; } } void Test9() { switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 0); switch (TakeOutParam(9, out var x9) ? x9 : 0) { case 9: Dummy(x9, 1); break; } break; } } void Test10() { switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) { case 10: var y10 = 12; Dummy(y10); break; } } //void Test11() //{ // switch (y11 + (TakeOutParam(11, out var x11) ? x11 : 0)) // { // case 11: // let y11 = 12; // Dummy(y11); // break; // } //} void Test14() { switch (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ? 1 : 0) { case 0: Dummy(x14); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (27,41): error CS0128: A local variable named 'x4' is already defined in this scope // switch (TakeOutParam(4, out var x4) ? x4 : 0) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(27, 41), // (37,41): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(5, out var x5) ? x5 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(37, 41), // (47,17): error CS0841: Cannot use local variable 'x6' before it is declared // switch (x6 + (TakeOutParam(6, out var x6) ? x6 : 0)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(47, 17), // (60,21): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(60, 21), // (71,23): error CS0841: Cannot use local variable 'x9' before it is declared // Dummy(x9, 0); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(71, 23), // (72,49): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // switch (TakeOutParam(9, out var x9) ? x9 : 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(72, 49), // (85,17): error CS0103: The name 'y10' does not exist in the current context // switch (y10 + (TakeOutParam(10, out var x10) ? x10 : 0)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 17), // (108,43): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(108, 43) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Switch_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) switch (TakeOutParam(1, out var x1) ? 1 : 0) { case 0: break; } Dummy(x1, 1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,15): error CS0103: The name 'x1' does not exist in the current context // Dummy(x1, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(19, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Switch_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (SwitchStatementSyntax)SyntaxFactory.ParseStatement(@" switch (Dummy(TakeOutParam(true, out var x1), x1)) {} "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, TakeOutParam(""Test1 {0}"", out var x1))) { case 0 when Dummy1(true, TakeOutParam(""case 0"", out var y1)): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) {} if (f) { switch (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_SwitchLabelGuard_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test1(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 1 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; case 2 when Dummy(TakeOutParam(true, out var x1), x1): Dummy(x1); break; } } void Test2(int val) { switch (val) { case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Dummy(x2); break; } } void Test3(int x3, int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x3), x3): Dummy(x3); break; } } void Test4(int val) { var x4 = 11; switch (val) { case 0 when Dummy(TakeOutParam(true, out var x4), x4): Dummy(x4); break; case 1 when Dummy(x4): Dummy(x4); break; } } void Test5(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x5), x5): Dummy(x5); break; } var x5 = 11; Dummy(x5); } //void Test6(int val) //{ // let x6 = 11; // switch (val) // { // case 0 when Dummy(x6): // Dummy(x6); // break; // case 1 when Dummy(TakeOutParam(true, out var x6), x6): // Dummy(x6); // break; // } //} //void Test7(int val) //{ // switch (val) // { // case 0 when Dummy(TakeOutParam(true, out var x7), x7): // Dummy(x7); // break; // } // let x7 = 11; // Dummy(x7); //} void Test8(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test9(int val) { switch (val) { case 0 when Dummy(x9): int x9 = 9; Dummy(x9); break; case 2 when Dummy(x9 = 9): Dummy(x9); break; case 1 when Dummy(TakeOutParam(true, out var x9), x9): Dummy(x9); break; } } //void Test10(int val) //{ // switch (val) // { // case 1 when Dummy(TakeOutParam(true, out var x10), x10): // Dummy(x10); // break; // case 0 when Dummy(x10): // let x10 = 10; // Dummy(x10); // break; // case 2 when Dummy(x10 = 10, x10): // Dummy(x10); // break; // } //} void Test11(int val) { switch (x11 ? val : 0) { case 0 when Dummy(x11): Dummy(x11, 0); break; case 1 when Dummy(TakeOutParam(true, out var x11), x11): Dummy(x11, 1); break; } } void Test12(int val) { switch (x12 ? val : 0) { case 0 when Dummy(TakeOutParam(true, out var x12), x12): Dummy(x12, 0); break; case 1 when Dummy(x12): Dummy(x12, 1); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case 1 when Dummy(TakeOutParam(true, out var x13), x13): Dummy(x13); break; } } void Test14(int val) { switch (val) { case 1 when Dummy(TakeOutParam(true, out var x14), x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test15(int val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x15), x15): case 1 when Dummy(TakeOutParam(true, out var x15), x15): Dummy(x15); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (30,31): error CS0841: Cannot use local variable 'x2' before it is declared // case 0 when Dummy(x2, TakeOutParam(true, out var x2)): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(30, 31), // (40,58): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x3), x3): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(40, 58), // (51,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x4), x4): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(51, 58), // (62,58): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 0 when Dummy(TakeOutParam(true, out var x5), x5): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(62, 58), // (102,95): error CS0128: A local variable named 'x8' is already defined in this scope // case 0 when Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(102, 95), // (112,31): error CS0841: Cannot use local variable 'x9' before it is declared // case 0 when Dummy(x9): Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(112, 31), // (119,58): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x9), x9): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(119, 58), // (144,17): error CS0103: The name 'x11' does not exist in the current context // switch (x11 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(144, 17), // (146,31): error CS0103: The name 'x11' does not exist in the current context // case 0 when Dummy(x11): Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(146, 31), // (147,23): error CS0103: The name 'x11' does not exist in the current context // Dummy(x11, 0); Diagnostic(ErrorCode.ERR_NameNotInContext, "x11").WithArguments("x11").WithLocation(147, 23), // (157,17): error CS0103: The name 'x12' does not exist in the current context // switch (x12 ? val : 0) Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(157, 17), // (162,31): error CS0103: The name 'x12' does not exist in the current context // case 1 when Dummy(x12): Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(162, 31), // (163,23): error CS0103: The name 'x12' does not exist in the current context // Dummy(x12, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x12").WithArguments("x12").WithLocation(163, 23), // (175,58): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x13), x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(175, 58), // (185,58): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case 1 when Dummy(TakeOutParam(true, out var x14), x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(185, 58), // (198,58): error CS0128: A local variable named 'x15' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(198, 58), // (198,64): error CS0165: Use of unassigned local variable 'x15' // case 1 when Dummy(TakeOutParam(true, out var x15), x15): Diagnostic(ErrorCode.ERR_UseDefViolation, "x15").WithArguments("x15").WithLocation(198, 64) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(6, x1Ref.Length); for (int i = 0; i < x1Decl.Length; i++) { VerifyModelForOutVar(model, x1Decl[i], x1Ref[i * 2], x1Ref[i * 2 + 1]); } var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(4, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref[0], x4Ref[1]); VerifyNotAnOutLocal(model, x4Ref[2]); VerifyNotAnOutLocal(model, x4Ref[3]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref[0], x5Ref[1]); VerifyNotAnOutLocal(model, x5Ref[2]); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(6, x9Ref.Length); VerifyNotAnOutLocal(model, x9Ref[0]); VerifyNotAnOutLocal(model, x9Ref[1]); VerifyNotAnOutLocal(model, x9Ref[2]); VerifyNotAnOutLocal(model, x9Ref[3]); VerifyModelForOutVar(model, x9Decl, x9Ref[4], x9Ref[5]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(5, x11Ref.Length); VerifyNotInScope(model, x11Ref[0]); VerifyNotInScope(model, x11Ref[1]); VerifyNotInScope(model, x11Ref[2]); VerifyModelForOutVar(model, x11Decl, x11Ref[3], x11Ref[4]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(5, x12Ref.Length); VerifyNotInScope(model, x12Ref[0]); VerifyModelForOutVar(model, x12Decl, x12Ref[1], x12Ref[2]); VerifyNotInScope(model, x12Ref[3]); VerifyNotInScope(model, x12Ref[4]); var x13Decl = GetOutVarDeclarations(tree, "x13").ToArray(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(2, x13Decl.Length); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl[0], x13Ref[0], x13Ref[1], x13Ref[2]); VerifyModelForOutVar(model, x13Decl[1], x13Ref[3], x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(4, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVar(model, x14Decl[1], isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x15Decl = GetOutVarDeclarations(tree, "x15").ToArray(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Decl.Length); Assert.Equal(3, x15Ref.Length); for (int i = 0; i < x15Ref.Length; i++) { VerifyModelForOutVar(model, x15Decl[0], x15Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x15Decl[1]); } [Fact] public void Scope_SwitchLabelGuard_02() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_03() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): while (TakeOutParam(x1, out var y1) && Print(y1)) break; break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_04() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): do val = 0; while (TakeOutParam(x1, out var y1) && Print(y1)); break; } } static bool Print(int x) { System.Console.WriteLine(x); return false; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_05() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): lock ((object)TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_06() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): if (TakeOutParam(x1, out var y1)) {} System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): switch (TakeOutParam(x1, out var y1)) { default: break; } System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_08() { var source = @" public class X { public static void Main() { foreach (var x in Test(1)) {} } static System.Collections.IEnumerable Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): yield return TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_09() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z1 = x1 > 0 & TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_10() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): a: TakeOutParam(x1, out var y1); System.Console.WriteLine(y1); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (14,1): warning CS0164: This label has not been referenced // a: TakeOutParam(x1, out var y1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(14, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_11() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): return TakeOutParam(x1, out var y1) && Print(y1); System.Console.WriteLine(y1); break; } return false; } static bool Print<T>(T x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (15,17): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(15, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelGuard_12() { var source = @" public class X { public static void Main() { Test(1); } static bool Test(int val) { try { switch (val) { case 1 when TakeOutParam(123, out var x1): throw Dummy(TakeOutParam(x1, out var y1), y1); System.Console.WriteLine(y1); break; } } catch {} return false; } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics( // (17,21): warning CS0162: Unreachable code detected // System.Console.WriteLine(y1); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(17, 21) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y1").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_13() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, z1) = (x1 > 0, TakeOutParam(x1, out var y1)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void Scope_SwitchLabelGuard_14() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var (z0, (z1, z2)) = (x1 > 0, (TakeOutParam(x1, out var y1), true)); System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.Equal("System.Boolean", model.GetTypeInfo(zRef).Type.ToTestDisplayString()); } [Fact] public void Scope_SwitchLabelPattern_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) { return true; } void Test8(object val) { switch (val) { case int x8 when Dummy(x8, TakeOutParam(false, out var x8), x8): Dummy(x8); break; } } void Test13() { switch (TakeOutParam(1, out var x13) ? x13 : 0) { case 0 when Dummy(x13): Dummy(x13); break; case int x13 when Dummy(x13): Dummy(x13); break; } } void Test14(object val) { switch (val) { case int x14 when Dummy(x14): Dummy(x14); Dummy(TakeOutParam(true, out var x14), x14); Dummy(x14); break; } } void Test16(object val) { switch (val) { case int x16 when Dummy(x16): case 1 when Dummy(TakeOutParam(true, out var x16), x16): Dummy(x16); break; } } void Test17(object val) { switch (val) { case 0 when Dummy(TakeOutParam(true, out var x17), x17): case int x17 when Dummy(x17): Dummy(x17); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,64): error CS0128: A local variable named 'x8' is already defined in this scope // when Dummy(x8, TakeOutParam(false, out var x8), x8): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(15, 64), // (28,22): error CS0136: A local or parameter named 'x13' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x13 when Dummy(x13): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x13").WithArguments("x13").WithLocation(28, 22), // (38,22): error CS0136: A local or parameter named 'x14' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case int x14 when Dummy(x14): Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x14").WithArguments("x14").WithLocation(38, 22), // (51,58): error CS0128: A local variable named 'x16' is already defined in this scope // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x16").WithArguments("x16").WithLocation(51, 58), // (51,64): error CS0165: Use of unassigned local variable 'x16' // case 1 when Dummy(TakeOutParam(true, out var x16), x16): Diagnostic(ErrorCode.ERR_UseDefViolation, "x16").WithArguments("x16").WithLocation(51, 64), // (62,22): error CS0128: A local variable named 'x17' is already defined in this scope // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_LocalDuplicate, "x17").WithArguments("x17").WithLocation(62, 22), // (62,37): error CS0165: Use of unassigned local variable 'x17' // case int x17 when Dummy(x17): Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(62, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); for (int i = 0; i < x8Ref.Length; i++) { VerifyNotAnOutLocal(model, x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl); var x13Decl = GetOutVarDeclarations(tree, "x13").Single(); var x13Ref = GetReferences(tree, "x13").ToArray(); Assert.Equal(5, x13Ref.Length); VerifyModelForOutVar(model, x13Decl, x13Ref[0], x13Ref[1], x13Ref[2]); VerifyNotAnOutLocal(model, x13Ref[3]); VerifyNotAnOutLocal(model, x13Ref[4]); var x14Decl = GetOutVarDeclarations(tree, "x14").Single(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(4, x14Ref.Length); VerifyNotAnOutLocal(model, x14Ref[0]); VerifyNotAnOutLocal(model, x14Ref[1]); VerifyNotAnOutLocal(model, x14Ref[2]); VerifyNotAnOutLocal(model, x14Ref[3]); VerifyModelForOutVar(model, x14Decl, isDelegateCreation: false, isExecutableCode: true, isShadowed: true); var x16Decl = GetOutVarDeclarations(tree, "x16").Single(); var x16Ref = GetReferences(tree, "x16").ToArray(); Assert.Equal(3, x16Ref.Length); for (int i = 0; i < x16Ref.Length; i++) { VerifyNotAnOutLocal(model, x16Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x16Decl); var x17Decl = GetOutVarDeclarations(tree, "x17").Single(); var x17Ref = GetReferences(tree, "x17").ToArray(); Assert.Equal(3, x17Ref.Length); VerifyModelForOutVar(model, x17Decl, x17Ref); } [Fact] public void Scope_ThrowStatement_01() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1() { throw Dummy(TakeOutParam(true, out var x1), x1); { throw Dummy(TakeOutParam(true, out var x1), x1); } throw Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { throw Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { throw Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); throw Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { throw Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); // throw Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ // throw Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) throw Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) throw Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); throw Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { throw Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,52): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 52), // (16,48): error CS0128: A local variable or function named 'x1' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 48), // (21,21): error CS0841: Cannot use local variable 'x2' before it is declared // throw Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 21), // (26,48): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // throw Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 48), // (33,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 48), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (39,9): warning CS0162: Unreachable code detected // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreachableCode, "var").WithLocation(39, 9), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,85): error CS0128: A local variable or function named 'x8' is already defined in this scope // throw Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 85), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (86,9): warning CS0162: Unreachable code detected // Dummy(x12); Diagnostic(ErrorCode.WRN_UnreachableCode, "Dummy").WithLocation(86, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl[0], x8Ref); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_ThrowStatement_02() { var source = @" public class X { public static void Main() { } System.Exception Dummy(params object[] x) { return null;} void Test1(bool val) { if (val) throw Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_ThrowStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (ThrowStatementSyntax)SyntaxFactory.ParseStatement(@" throw Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(TakeOutParam(""throw"", out var x2), x2); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(TakeOutParam(""throw 1"", out var x2), x2); if (!val) { throw Dummy(TakeOutParam(""throw 2"", out var x2), x2); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[0]); VerifyModelForOutVar(model, x2Decl[1], x2Ref[1]); } [Fact] public void Scope_Using_01() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,49): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 49), // (35,22): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 22), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,53): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 53), // (68,35): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 35), // (86,35): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 35), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (var d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (var d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (var d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (var d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); } void Test6() { using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); } void Test7() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } } void Test8() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } } void Test10() { using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; } //void Test13() //{ // using (System.IDisposable d = Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; //} void Test14() { using (System.IDisposable d = Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,72): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable d = Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 72), // (35,45): error CS0841: Cannot use local variable 'x6' before it is declared // using (System.IDisposable d = Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 45), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,76): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (System.IDisposable c = Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 76), // (68,58): error CS0103: The name 'y10' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 58), // (86,58): error CS0103: The name 'y12' does not exist in the current context // using (System.IDisposable d = Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 58), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,69): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 69) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_Using_04() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,58): error CS0128: A local variable named 'x1' is already defined in this scope // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (12,63): error CS0841: Cannot use local variable 'x1' before it is declared // using (var x1 = Dummy(TakeOutParam(true, out var x1), x1)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(12, 63), // (20,73): error CS0128: A local variable named 'x2' is already defined in this scope // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73), // (20,78): error CS0165: Use of unassigned local variable 'x2' // using (System.IDisposable x2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 78) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_Using_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d = Dummy(TakeOutParam(true, out var x1), x1), x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x2), x2), d2 = Dummy(TakeOutParam(true, out var x2), x2)) { Dummy(x2); } } void Test3() { using (System.IDisposable d1 = Dummy(TakeOutParam(true, out var x3), x3), d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2 = Dummy(TakeOutParam(true, out var x4), x4)) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void Scope_While_01() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { while (TakeOutParam(true, out var x1) && x1) { Dummy(x1); } } void Test2() { while (TakeOutParam(true, out var x2) && x2) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); while (TakeOutParam(true, out var x4) && x4) Dummy(x4); } void Test6() { while (x6 && TakeOutParam(true, out var x6)) Dummy(x6); } void Test7() { while (TakeOutParam(true, out var x7) && x7) { var x7 = 12; Dummy(x7); } } void Test8() { while (TakeOutParam(true, out var x8) && x8) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { while (TakeOutParam(true, out var x9) && x9) { Dummy(x9); while (TakeOutParam(true, out var x9) && x9) // 2 Dummy(x9); } } void Test10() { while (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // while (TakeOutParam(y11, out var x11)) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { while (TakeOutParam(y12, out var x12)) var y12 = 12; } //void Test13() //{ // while (TakeOutParam(y13, out var x13)) // let y13 = 12; //} void Test14() { while (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,43): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 43), // (35,16): error CS0841: Cannot use local variable 'x6' before it is declared // while (x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 16), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 47), // (68,29): error CS0103: The name 'y10' does not exist in the current context // while (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 29), // (86,29): error CS0103: The name 'y12' does not exist in the current context // while (TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 29), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,46): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_While_02() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { if (true) while (TakeOutParam(true, out var x1)) { ; } x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (18,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(18, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_While_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (WhileStatementSyntax)SyntaxFactory.ParseStatement(@" while (Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1)) f = false; f = true; if (f) { while (Dummy(f, TakeOutParam((f ? 3 : 4), out var x1), x1)) f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 4"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, TakeOutParam(f, out var x1), x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Scope_Yield_01() { var source = @" using System.Collections; public class X { public static void Main() { } object Dummy(params object[] x) { return null;} IEnumerable Test1() { yield return Dummy(TakeOutParam(true, out var x1), x1); { yield return Dummy(TakeOutParam(true, out var x1), x1); } yield return Dummy(TakeOutParam(true, out var x1), x1); } IEnumerable Test2() { yield return Dummy(x2, TakeOutParam(true, out var x2)); } IEnumerable Test3(int x3) { yield return Dummy(TakeOutParam(true, out var x3), x3); } IEnumerable Test4() { var x4 = 11; Dummy(x4); yield return Dummy(TakeOutParam(true, out var x4), x4); } IEnumerable Test5() { yield return Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //IEnumerable Test6() //{ // let x6 = 11; // Dummy(x6); // yield return Dummy(TakeOutParam(true, out var x6), x6); //} //IEnumerable Test7() //{ // yield return Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} IEnumerable Test8() { yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } IEnumerable Test9(bool y9) { if (y9) yield return Dummy(TakeOutParam(true, out var x9), x9); } IEnumerable Test11() { Dummy(x11); yield return Dummy(TakeOutParam(true, out var x11), x11); } IEnumerable Test12() { yield return Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (16,59): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(16, 59), // (18,55): error CS0128: A local variable or function named 'x1' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(18, 55), // (23,28): error CS0841: Cannot use local variable 'x2' before it is declared // yield return Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(23, 28), // (28,55): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // yield return Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(28, 55), // (35,55): error CS0128: A local variable or function named 'x4' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(35, 55), // (41,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(41, 13), // (41,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(41, 13), // (61,92): error CS0128: A local variable or function named 'x8' is already defined in this scope // yield return Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(61, 92), // (72,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(72, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_Yield_02() { var source = @" using System.Collections; public class X { public static void Main() { } IEnumerable Test1() { if (true) yield return TakeOutParam(true, out var x1); x1++; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref); } [Fact] public void Scope_Yield_03() { var source = @" using System.Collections; public class X { public static void Main() { } void Dummy(params object[] x) {} IEnumerable Test1() { yield return 0; SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (YieldStatementSyntax)SyntaxFactory.ParseStatement(@" yield return Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); yield return Dummy(TakeOutParam(""yield2"", out var x2), x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(TakeOutParam(""yield1"", out var x1), x1); if (f) { yield return Dummy(TakeOutParam(""yield2"", out var x1), x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void Scope_LabeledStatement_01() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { a: Dummy(TakeOutParam(true, out var x1), x1); { b: Dummy(TakeOutParam(true, out var x1), x1); } c: Dummy(TakeOutParam(true, out var x1), x1); } void Test2() { a: Dummy(x2, TakeOutParam(true, out var x2)); } void Test3(int x3) { a: Dummy(TakeOutParam(true, out var x3), x3); } void Test4() { var x4 = 11; Dummy(x4); a: Dummy(TakeOutParam(true, out var x4), x4); } void Test5() { a: Dummy(TakeOutParam(true, out var x5), x5); var x5 = 11; Dummy(x5); } //void Test6() //{ // let x6 = 11; // Dummy(x6); //a: Dummy(TakeOutParam(true, out var x6), x6); //} //void Test7() //{ //a: Dummy(TakeOutParam(true, out var x7), x7); // let x7 = 11; // Dummy(x7); //} void Test8() { a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); } void Test9(bool y9) { if (y9) a: Dummy(TakeOutParam(true, out var x9), x9); } System.Action Test10(bool y10) { return () => { if (y10) a: Dummy(TakeOutParam(true, out var x10), x10); }; } void Test11() { Dummy(x11); a: Dummy(TakeOutParam(true, out var x11), x11); } void Test12() { a: Dummy(TakeOutParam(true, out var x12), x12); Dummy(x12); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (14,46): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(14, 46), // (16,42): error CS0128: A local variable or function named 'x1' is already defined in this scope // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(16, 42), // (12,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(12, 1), // (14,1): warning CS0164: This label has not been referenced // b: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(14, 1), // (16,1): warning CS0164: This label has not been referenced // c: Dummy(TakeOutParam(true, out var x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(16, 1), // (21,15): error CS0841: Cannot use local variable 'x2' before it is declared // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(21, 15), // (21,1): warning CS0164: This label has not been referenced // a: Dummy(x2, TakeOutParam(true, out var x2)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(21, 1), // (26,42): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(26, 42), // (26,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x3), x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(26, 1), // (33,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(33, 42), // (33,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x4), x4); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(33, 1), // (39,13): error CS0128: A local variable or function named 'x5' is already defined in this scope // var x5 = 11; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(39, 13), // (38,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x5), x5); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(38, 1), // (39,13): warning CS0219: The variable 'x5' is assigned but its value is never used // var x5 = 11; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x5").WithArguments("x5").WithLocation(39, 13), // (59,79): error CS0128: A local variable or function named 'x8' is already defined in this scope // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(59, 79), // (59,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x8), x8, TakeOutParam(false, out var x8), x8); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(59, 1), // (65,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x9), x9);").WithLocation(65, 1), // (65,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x9), x9); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(65, 1), // (73,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x10), x10);").WithLocation(73, 1), // (73,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x10), x10); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(73, 1), // (79,15): error CS0841: Cannot use local variable 'x11' before it is declared // Dummy(x11); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x11").WithArguments("x11").WithLocation(79, 15), // (80,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x11), x11); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(80, 1), // (85,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x12), x12); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(85, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl[2]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVar(model, x5Decl, x5Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Decl.Length); Assert.Equal(2, x8Ref.Length); for (int i = 0; i < x8Decl.Length; i++) { VerifyModelForOutVar(model, x8Decl[0], x8Ref[i]); } VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); var x9Decl = GetOutVarDeclarations(tree, "x9").Single(); var x9Ref = GetReferences(tree, "x9").Single(); VerifyModelForOutVar(model, x9Decl, x9Ref); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(2, x11Ref.Length); VerifyModelForOutVar(model, x11Decl, x11Ref); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(2, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref); } [Fact] public void Scope_LabeledStatement_02() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { if (true) a: Dummy(TakeOutParam(true, out var x1)); x1++; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (13,1): error CS1023: Embedded statement cannot be a declaration or labeled statement // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "a: Dummy(TakeOutParam(true, out var x1));").WithLocation(13, 1), // (15,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(15, 9), // (13,1): warning CS0164: This label has not been referenced // a: Dummy(TakeOutParam(true, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0]); VerifyNotInScope(model, x1Ref[0]); } [Fact] public void Scope_LabeledStatement_03() { var source = @" public class X { public static void Main() { } void Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LabeledStatementSyntax)SyntaxFactory.ParseStatement(@" a: b: Dummy(TakeOutParam(true, out var x1), x1); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { a: b: c:Test2(Test1(out int x1), x1); System.Console.Write(x1); return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "11").VerifyDiagnostics( // (11,1): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(11, 1), // (11,4): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(11, 4), // (11,7): warning CS0164: This label has not been referenced // a: b: c:Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(11, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(Test1(out int x1), x1); } return null; } static object Test1(out int x) { x = 1; return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "1").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(Test1(out int x1), x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void DataFlow_01() { var text = @" public class Cls { public static void Main() { Test(out int x1, x1); } static void Test(out int x, int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_02() { var text = @" public class Cls { public static void Main() { Test(out int x1, ref x1); } static void Test(out int x, ref int y) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,22): error CS0165: Use of unassigned local variable 'x1' // ref x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void DataFlow_03() { var text = @" public class Cls { public static void Main() { Test(out int x1); var x2 = 1; } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,13): warning CS0219: The variable 'x2' is assigned but its value is never used // var x2 = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x2").WithArguments("x2").WithLocation(7, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Single(); var dataFlow = model.AnalyzeDataFlow(x2Decl); Assert.True(dataFlow.Succeeded); Assert.Equal("System.Int32 x2", dataFlow.VariablesDeclared.Single().ToTestDisplayString()); Assert.Equal("System.Int32 x1", dataFlow.WrittenOutside.Single().ToTestDisplayString()); } [Fact] public void TypeMismatch_01() { var text = @" public class Cls { public static void Main() { Test(out int x1); } static void Test(out short x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS1503: Argument 1: cannot convert from 'out int' to 'out short' // Test(out int x1); Diagnostic(ErrorCode.ERR_BadArgType, "int x1").WithArguments("1", "out int", "out short").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_01() { var text = @" public class Cls { public static void Main() { Test(int x1); Test(ref int x2); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,14): error CS1525: Invalid expression term 'int' // Test(int x1); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 14), // (6,18): error CS1003: Syntax error, ',' expected // Test(int x1); Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 18), // (7,18): error CS1525: Invalid expression term 'int' // Test(ref int x2); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 18), // (7,22): error CS1003: Syntax error, ',' expected // Test(ref int x2); Diagnostic(ErrorCode.ERR_SyntaxError, "x2").WithArguments(",", "").WithLocation(7, 22), // (6,18): error CS0103: The name 'x1' does not exist in the current context // Test(int x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 18), // (7,22): error CS0103: The name 'x2' does not exist in the current context // Test(ref int x2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 22) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void Parse_02() { var text = @" public class Cls { public static void Main() { Test(out int x1.); } static void Test(out int x) { x = 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,24): error CS1003: Syntax error, ',' expected // Test(out int x1.); Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [Fact] public void Parse_03() { var text = @" public class Cls { public static void Main() { Test(out System.Collections.Generic.IEnumerable<System.Int32>); } static void Test(out System.Collections.Generic.IEnumerable<System.Int32> x) { x = null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,18): error CS0118: 'IEnumerable<int>' is a type but is used like a variable // Test(out System.Collections.Generic.IEnumerable<System.Int32>); Diagnostic(ErrorCode.ERR_BadSKknown, "System.Collections.Generic.IEnumerable<System.Int32>").WithArguments("System.Collections.Generic.IEnumerable<int>", "type", "variable").WithLocation(6, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree).Any()); } [Fact] public void GetAliasInfo_01() { var text = @" using a = System.Int32; public class Cls { public static void Main() { Test1(out a x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GetAliasInfo_02() { var text = @" using var = System.Int32; public class Cls { public static void Main() { Test1(out var x1); } static object Test1(out int x) { x = 123; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void VarIsNotVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out var x) { x = new var() {val = 123}; return null; } static void Test2(object x, var y) { System.Console.WriteLine(y.val); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void VarIsNotVar_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1); } struct var { public int val; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0103: The name 'Test1' does not exist in the current context // Test1(out var x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 9), // (11,20): warning CS0649: Field 'Cls.var.val' is never assigned to, and will always have its default value 0 // public int val; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "val").WithArguments("Cls.var.val", "0").WithLocation(11, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); Assert.Equal("Cls.var", ((ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void SimpleVar_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static void Test2(object x, object y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,15): error CS0103: The name 'Test1' does not exist in the current context // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test1").WithArguments("Test1").WithLocation(6, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void SimpleVar_03() { var text = @" public class Cls { public static void Main() { Test1(out var x1, out x1); } static object Test1(out int x, out int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,23): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // out x1); Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_04() { var text = @" public class Cls { public static void Main() { Test1(out var x1, Test1(out x1, 3)); } static object Test1(out int x, int x2) { x = 123; x2 = 124; return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,25): error CS8181: Reference to an implicitly-typed out variable 'x1' is not permitted in the same argument list. // Test1(out x1, Diagnostic(ErrorCode.ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList, "x1").WithArguments("x1").WithLocation(7, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_05() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(ref int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgRef, "var x1").WithArguments("1", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_06() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(int x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,25): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("System.Int32 x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_07() { var text = @" public class Cls { public static void Main() { dynamic x = null; Test2(x.Test1(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,31): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x.Test1(out var x1), Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 31) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_08() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var x1), x1); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_09() { var text = @" public class Cls { public static void Main() { Test2(new System.Action(out var x1), x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,37): error CS0149: Method name expected // Test2(new System.Action(out var x1), Diagnostic(ErrorCode.ERR_MethodNameExpected, "var x1").WithLocation(6, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, isDelegateCreation: true, isExecutableCode: true, isShadowed: false, verifyDataFlow: true, references: x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("var x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void ConstructorInitializers_01() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x, object y) { System.Console.WriteLine(y); } public Test2() : this(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (25,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : this(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(25, 26) ); var initializer = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); var typeInfo = model.GetTypeInfo(initializer); var symbolInfo = model.GetSymbolInfo(initializer); var group = model.GetMemberGroup(initializer); Assert.Equal("System.Void", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Cls.Test2..ctor(System.Object x, System.Object y)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Empty(group); // https://github.com/dotnet/roslyn/issues/24936 } [Fact] public void ConstructorInitializers_02() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { public Test2(object x, object y) { System.Console.WriteLine(y); } } class Test3 : Test2 { public Test3() : base(Test1(out var x1), x1) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (29,26): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // : base(Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "var x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(29, 26) ); } [Fact] public void ConstructorInitializers_03() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} class Test2 { Test2(out int x) { x = 2; } public Test2() : this(out var x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] public void ConstructorInitializers_04() { var text = @" public class Cls { public static void Main() { Do(new Test3()); } static void Do(object x){} class Test2 { public Test2(out int x) { x = 1; } } class Test3 : Test2 { public Test3() : base(out var x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(GetVariableDesignation(x1Decl))).Type.ToTestDisplayString()); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_05() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(System.Func<object> x) { System.Console.WriteLine(x()); } public Test2() : this(() => { Test1(out var x1); return x1; }) {} } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_06() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_07() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_08() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object x) { } public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (23,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2() Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2() : this(Test1(out var x1)) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(23, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var analyzer = new ConstructorInitializers_08_SyntaxAnalyzer(); CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular) .GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.True(analyzer.ActionFired); } private class ConstructorInitializers_08_SyntaxAnalyzer : DiagnosticAnalyzer { public bool ActionFired { get; private set; } private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle, SyntaxKind.ThisConstructorInitializer); } private void Handle(SyntaxNodeAnalysisContext context) { ActionFired = true; var tree = context.Node.SyntaxTree; var model = context.SemanticModel; var constructorDeclaration = (ConstructorDeclarationSyntax)context.Node.Parent; SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(constructorDeclaration)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[constructorDeclaration]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Initializer).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.Body).IsDefaultOrEmpty); Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(constructorDeclaration.ExpressionBody).IsDefaultOrEmpty); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Decl)); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[0])); Assert.Same(mm, syntaxTreeModel.GetMemberModel(x1Ref[1])); } } [Fact] public void ConstructorInitializers_09() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_10() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_11() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (21,37): error CS0165: Use of unassigned local variable 'x1' // => System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(21, 37) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_12() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), 1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (22,38): error CS0165: Use of unassigned local variable 'x1' // System.Console.WriteLine(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(22, 38) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_13() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_14() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_15() { var text = @" public class Cls { public static void Main() { } public static bool Test1(out int x) { throw null; } class Test2 { Test2(bool x, int y) { } public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (19,9): error CS8057: Block bodies and expression bodies cannot both be provided. // public Test2(bool a) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"public Test2(bool a) : this(a && Test1(out var x1), x1) { System.Console.WriteLine(x1); } => System.Console.WriteLine(x1);").WithLocation(19, 9), // (20,40): error CS0165: Use of unassigned local variable 'x1' // : this(a && Test1(out var x1), x1) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(20, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_16() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) { System.Console.WriteLine(x1); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ConstructorInitializers_17() { var text = @" public class Cls { public static void Main() { Do(new Test2()); } static void Do(object x){} public static object Test1(out int x) { x = 123; return null; } class Test2 { Test2(object a, object b, ref int x) { System.Console.WriteLine(x); x++; } public Test2() : this(Test1(out var x1), ((System.Func<int>)(() => x1++))(), ref x1) => System.Console.WriteLine(x1); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void SimpleVar_14() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out dynamic x) { x = 123; return null; } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); Assert.Equal("dynamic x1", model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)).ToTestDisplayString()); } [Fact] public void SimpleVar_15() { var text = @" public class Cls { public static void Main() { Test2(new Test1(out var var), var); } class Test1 { public Test1(out int x) { x = 123; } } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var varDecl = GetOutVarDeclaration(tree, "var"); var varRef = GetReferences(tree, "var").Skip(1).Single(); VerifyModelForOutVar(model, varDecl, varRef); } [Fact] public void SimpleVar_16() { var text = @" public class Cls { public static void Main() { if (Test1(out var x1)) { System.Console.WriteLine(x1); } } static bool Test1(out int x) { x = 123; return true; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"123").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void VarAndBetterness_01() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); Test2(out var x2, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, string y) { x = 124; System.Console.WriteLine(x); return null; } static object Test2(out int x, string y) { x = 125; System.Console.WriteLine(x); return null; } static object Test2(out short x, object y) { x = 126; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124 125").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); var x2Decl = GetOutVarDeclaration(tree, "x2"); VerifyModelForOutVar(model, x2Decl); } [Fact] public void VarAndBetterness_02() { var text = @" public class Cls { public static void Main() { Test1(out var x1, null); } static object Test1(out int x, object y) { x = 123; System.Console.WriteLine(x); return null; } static object Test1(out short x, object y) { x = 124; System.Console.WriteLine(x); return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Cls.Test1(out int, object)' and 'Cls.Test1(out short, object)' // Test1(out var x1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "Test1").WithArguments("Cls.Test1(out int, object)", "Cls.Test1(out short, object)").WithLocation(6, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVar(model, x1Decl); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_01() { var text = @" public class Cls { public static void Main() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_02() { var text = @" public class Cls { public static void Main() { Test2(Test1(out System.ArgIterator x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void RestrictedTypes_03() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out var x1), x1); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (11,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(11, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out var x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(8, 25), // (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void RestrictedTypes_04() { var text = @" public class Cls { public static void Main() {} async void Test() { Test2(Test1(out System.ArgIterator x1), x1); var x = default(System.ArgIterator); } static object Test1(out System.ArgIterator x) { x = default(System.ArgIterator); return null; } static void Test2(object x, System.ArgIterator y) { } }"; var compilation = CreateCompilation(text, targetFramework: TargetFramework.Mscorlib45, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // static object Test1(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(12, 25), // (8,25): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // Test2(Test1(out System.ArgIterator x1), x1); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 25), // (9,9): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions. // var x = default(System.ArgIterator); Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "var").WithArguments("System.ArgIterator").WithLocation(9, 9), // (6,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void Test() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Test").WithLocation(6, 16) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void ElementAccess_01() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out var x1]); Test2(x1); Test2(x[out var _]); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(x[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25), // (9,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(9, 21), // (9,21): error CS8183: Cannot infer the type of implicitly-typed discard. // Test2(x[out var _]); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(9, 21) ); } [Fact] public void PointerAccess_01() { var text = @" public class Cls { public static unsafe void Main() { int* p = (int*)0; Test2(p[out var x1]); Test2(x1); } static void Test2(object x) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var model = compilation.GetSemanticModel(tree); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(7, 21), // (7,25): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // Test2(p[out var x1]); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 25) ); } [Fact] public void ElementAccess_02() { var text = @" public class Cls { public static void Main() { var x = new [] {1}; Test2(x[out int x1], x1); } static void Test2(object x, object y) { System.Console.WriteLine(y); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,21): error CS1615: Argument 1 may not be passed with the 'out' keyword // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "int x1").WithArguments("1", "out").WithLocation(7, 21), // (7,21): error CS0165: Use of unassigned local variable 'x1' // Test2(x[out int x1], x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x1").WithArguments("x1").WithLocation(7, 21) ); } [Fact] [WorkItem(12058, "https://github.com/dotnet/roslyn/issues/12058")] public void MissingArgumentAndNamedOutVarArgument() { var source = @"class Program { public static void Main(string[] args) { if (M(s: out var s)) { string s2 = s; } } public static bool M(int i, out string s) { s = i.ToString(); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (5,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'Program.M(int, out string)' // if (M(s: out var s)) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("i", "Program.M(int, out string)").WithLocation(5, 13) ); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_01() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x); System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"124").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_02() { var text = @" public class Cls { public static void Main() { var y = Test1(out int x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_03() { var text = @" public class Cls { public static void Main() { var y = Test1(out var x) + x; System.Console.WriteLine(y); } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReference(tree, "y"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_04() { var text = @" public class Cls { public static void Main() { for (var y = Test1(out var x) + x; y != 0 ; y = 0) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(12266, "https://github.com/dotnet/roslyn/issues/12266")] public void LocalVariableTypeInferenceAndOutVar_05() { var text = @" public class Cls { public static void Main() { foreach (var y in new [] {Test1(out var x) + x}) { System.Console.WriteLine(y); } } static int Test1(out int x) { x = 123; return 124; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"247").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yRef = GetReferences(tree, "y").Last(); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_06() { var text = @" public class Cls { public static void Main() { Test1(x: 1, out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( // (6,21): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "out var y").WithArguments("7.2").WithLocation(6, 21), // (6,25): error CS1620: Argument 2 must be passed with the 'ref' keyword // Test1(x: 1, out var y); Diagnostic(ErrorCode.ERR_BadArgRef, "var y").WithArguments("2", "ref").WithLocation(6, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); VerifyModelForOutVar(model, yDecl, GetReferences(tree, "y").ToArray()); } [Fact] [WorkItem(15732, "https://github.com/dotnet/roslyn/issues/15732")] public void LocalVariableTypeInferenceAndOutVar_07() { var text = @" public class Cls { public static void Main() { int x = 0; Test1(y: ref x, y: out var y); System.Console.WriteLine(y); } static void Test1(int x, ref int y) { } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Cls.Test1(int, ref int)' // Test1(y: ref x, y: out var y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Test1").WithArguments("x", "Cls.Test1(int, ref int)").WithLocation(7, 9)); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetDeclaration(tree, "y"); var yRef = GetReferences(tree, "y").ToArray(); Assert.Equal(3, yRef.Length); Assert.Equal("System.Console.WriteLine(y)", yRef[2].Parent.Parent.Parent.ToString()); VerifyModelForOutVar(model, yDecl, yRef[2]); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamic() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int z]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @"{ // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) //z IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret }"); } [Fact] public void IndexingDynamicWithDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this CompileAndVerify(text, references: new[] { CSharpRef }).VerifyIL("Cls.Main()", @" { // Code size 87 (0x57) .maxstack 7 .locals init (object V_0, //d int V_1) IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0007: brtrue.s IL_003e IL_0009: ldc.i4.0 IL_000a: ldtoken ""Cls"" IL_000f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0014: ldc.i4.2 IL_0015: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001a: dup IL_001b: ldc.i4.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0023: stelem.ref IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.s 17 IL_0028: ldnull IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002e: stelem.ref IL_002f: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0034: call ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0039: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_003e: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_0043: ldfld ""<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>>.Target"" IL_0048: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>> Cls.<>o__0.<>p__0"" IL_004d: ldloc.0 IL_004e: ldloca.s V_1 IL_0050: callvirt ""dynamic <>F{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, int, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref int)"" IL_0055: pop IL_0056: ret } "); } [Fact] public void IndexingDynamicWithVarDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var _]; } }"; // the C# dynamic binder does not support ref or out indexers, so we don't run this var comp = CreateCompilation(text, options: TestOptions.DebugDll, references: new[] { CSharpRef }); comp.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out var _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "var _").WithLocation(7, 23) ); } [Fact] public void IndexingDynamicWithShortDiscard() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out _]; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,23): error CS8183: Cannot infer the type of implicitly-typed discard. // var x = d[out _]; Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 23) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutVar() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out var x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.True(x1.Type.IsErrorType()); VerifyModelForOutVar(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var x = d[out var x1] + x1; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(7, 27) ); } [Fact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void IndexingDynamicWithOutInt() { var text = @" public class Cls { public static void Main() { dynamic d = null; var x = d[out int x1] + x1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); var x1 = (ILocalSymbol)model.GetDeclaredSymbol(GetVariableDesignation(x1Decl)); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [ClrOnlyFact, WorkItem(13219, "https://github.com/dotnet/roslyn/issues/13219")] public void OutVariableDeclarationInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; return 2; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.2 ret } // i = 3; return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.3 stind.i4 ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 4; return 5; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.5 ret } // i = 6; return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.6 stind.i4 ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} x1] + "" "" + x1); ia.P[out {0} x2] = 4; Console.WriteLine(x2); Console.WriteLine(ia[out {0} x3] + "" "" + x3); ia[out {0} x4] = 4; Console.WriteLine(x4); }} }}"; string[] fillIns = new[] { "int", "var" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(1, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref[0]).Type.ToTestDisplayString()); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Ref.Length); VerifyModelForOutVar(model, x3Decl, x3Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x3Ref[0]).Type.ToTestDisplayString()); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(1, x4Ref.Length); VerifyModelForOutVar(model, x4Decl, x4Ref); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref[0]).Type.ToTestDisplayString()); CompileAndVerify(source2, references: new[] { reference1 }, expectedOutput: @"2 1 3 5 4 6") .VerifyIL("B.Main()", @"{ // Code size 113 (0x71) .maxstack 4 .locals init (int V_0, //x1 int V_1, //x2 int V_2, //x3 int V_3, //x4 int V_4) IL_0000: newobj ""A..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: callvirt ""int IA.P[out int].get"" IL_000d: stloc.s V_4 IL_000f: ldloca.s V_4 IL_0011: call ""string int.ToString()"" IL_0016: ldstr "" "" IL_001b: ldloca.s V_0 IL_001d: call ""string int.ToString()"" IL_0022: call ""string string.Concat(string, string, string)"" IL_0027: call ""void System.Console.WriteLine(string)"" IL_002c: dup IL_002d: ldloca.s V_1 IL_002f: ldc.i4.4 IL_0030: callvirt ""void IA.P[out int].set"" IL_0035: ldloc.1 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: dup IL_003c: ldloca.s V_2 IL_003e: callvirt ""int IA.this[out int].get"" IL_0043: stloc.s V_4 IL_0045: ldloca.s V_4 IL_0047: call ""string int.ToString()"" IL_004c: ldstr "" "" IL_0051: ldloca.s V_2 IL_0053: call ""string int.ToString()"" IL_0058: call ""string string.Concat(string, string, string)"" IL_005d: call ""void System.Console.WriteLine(string)"" IL_0062: ldloca.s V_3 IL_0064: ldc.i4.4 IL_0065: callvirt ""void IA.this[out int].set"" IL_006a: ldloc.3 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret }"); } } [ClrOnlyFact] public void OutVariableDiscardInIndex() { var source1 = @".class interface public abstract import IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .method public abstract virtual instance int32 get_Item([out] int32& i) { } .method public abstract virtual instance void set_Item([out] int32& i, int32 v) { } .property instance int32 Item([out] int32&) { .get instance int32 IA::get_Item([out] int32&) .set instance void IA::set_Item([out] int32&, int32) } .method public abstract virtual instance int32 get_P([out] int32& i) { } .method public abstract virtual instance void set_P([out] int32& i, int32 v) { } .property instance int32 P([out] int32&) { .get instance int32 IA::get_P([out] int32&) .set instance void IA::set_P([out] int32&, int32) } } .class public A implements IA { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method public hidebysig specialname rtspecialname instance void .ctor() { ret } // i = 1; System.Console.WriteLine(11); return 111; .method public virtual instance int32 get_P([out] int32& i) { ldarg.1 ldc.i4.1 stind.i4 ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x06F ret } // i = 2; System.Console.Write(22); return; .method public virtual instance void set_P([out] int32& i, int32 v) { ldarg.1 ldc.i4.2 stind.i4 ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P([out] int32&) { .get instance int32 A::get_P([out] int32&) .set instance void A::set_P([out] int32&, int32) } // i = 3; System.Console.WriteLine(33) return 333; .method public virtual instance int32 get_Item([out] int32& i) { ldarg.1 ldc.i4.3 stind.i4 ldc.i4.s 33 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4 0x14D ret } // i = 4; System.Console.WriteLine(44); return; .method public virtual instance void set_Item([out] int32& i, int32 v) { ldarg.1 ldc.i4.4 stind.i4 ldc.i4.s 44 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 Item([out] int32&) { .get instance int32 A::get_Item([out] int32&) .set instance void A::set_Item([out] int32&, int32) } }"; var reference1 = CompileIL(source1); var source2Template = @"using System; class B {{ public static void Main() {{ A a = new A(); IA ia = a; Console.WriteLine(ia.P[out {0} _]); ia.P[out {0} _] = 4; Console.WriteLine(ia[out {0} _]); ia[out {0} _] = 4; }} }}"; string[] fillIns = new[] { "int", "var", "" }; foreach (var fillIn in fillIns) { var source2 = string.Format(source2Template, fillIn); var compilation = CreateCompilation(source2, references: new[] { reference1 }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"11 111 22 33 333 44") .VerifyIL("B.Main()", @" { // Code size 58 (0x3a) .maxstack 3 .locals init (A V_0, //a IA V_1, //ia int V_2) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloca.s V_2 IL_000c: callvirt ""int IA.P[out int].get"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ldloc.1 IL_0018: ldloca.s V_2 IL_001a: ldc.i4.4 IL_001b: callvirt ""void IA.P[out int].set"" IL_0020: nop IL_0021: ldloc.1 IL_0022: ldloca.s V_2 IL_0024: callvirt ""int IA.this[out int].get"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ldloc.1 IL_0030: ldloca.s V_2 IL_0032: ldc.i4.4 IL_0033: callvirt ""void IA.this[out int].set"" IL_0038: nop IL_0039: ret }"); } } [Fact] public void ElementAccess_04() { var text = @" using System.Collections.Generic; public class Cls { public static void Main() { var list = new Dictionary<int, long> { [out var x1] = 3, [out var _] = 4, [out _] = 5 }; System.Console.Write(x1); System.Console.Write(_); { int _ = 1; var list2 = new Dictionary<int, long> { [out _] = 6 }; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type.ToTestDisplayString()); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); compilation.VerifyDiagnostics( // (9,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var x1] = 3, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(9, 18), // (10,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out var _] = 4, Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var _").WithArguments("1", "out").WithLocation(10, 18), // (11,18): error CS1615: Argument 1 may not be passed with the 'out' keyword // [out _] = 5 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(11, 18), // (14,30): error CS0103: The name '_' does not exist in the current context // System.Console.Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(14, 30), // (18,58): error CS1615: Argument 1 may not be passed with the 'out' keyword // var list2 = new Dictionary<int, long> { [out _] = 6 }; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "_").WithArguments("1", "out").WithLocation(18, 58) ); } [Fact] public void ElementAccess_05() { var text = @" public class Cls { public static void Main() { int[out var x1] a = null; // fatal syntax error - 'out' is skipped int b(out var x2) = null; // parsed as a local function with syntax error int c[out var x3] = null; // fatal syntax error - 'out' is skipped int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator x4 = 0; } }"; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Equal(1, compilation.SyntaxTrees[0].GetRoot().DescendantNodesAndSelf().OfType<DeclarationExpressionSyntax>().Count()); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(compilation.GetSemanticModel(tree).GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); compilation.VerifyDiagnostics( // (6,13): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 13), // (6,21): error CS1003: Syntax error, ',' expected // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 21), // (7,27): error CS1002: ; expected // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(7, 27), // (7,27): error CS1525: Invalid expression term '=' // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(7, 27), // (8,14): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_CStyleArray, "[out var x3]").WithLocation(8, 14), // (8,15): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 15), // (8,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "var").WithLocation(8, 19), // (8,23): error CS1003: Syntax error, ',' expected // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 23), // (8,23): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "x3").WithLocation(8, 23), // (10,17): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x4").WithLocation(10, 17), // (10,17): error CS1003: Syntax error, '[' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(10, 17), // (10,28): error CS1003: Syntax error, ']' expected // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(10, 28), // (6,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[out var x1]").WithLocation(6, 12), // (6,17): error CS0103: The name 'var' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 17), // (6,21): error CS0103: The name 'x1' does not exist in the current context // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 21), // (7,13): error CS8112: 'b(out var)' is a local function and must therefore always have a body. // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "b").WithArguments("b(out var)").WithLocation(7, 13), // (7,19): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(7, 19), // (8,29): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 29), // (8,19): error CS0103: The name 'var' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19), // (8,23): error CS0103: The name 'x3' does not exist in the current context // int c[out var x3] = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(8, 23), // (7,13): error CS0177: The out parameter 'x2' must be assigned to before control leaves the current method // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.ERR_ParamUnassigned, "b").WithArguments("x2").WithLocation(7, 13), // (6,25): warning CS0219: The variable 'a' is assigned but its value is never used // int[out var x1] a = null; // fatal syntax error - 'out' is skipped Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(6, 25), // (10,13): warning CS0168: The variable 'd' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "d").WithArguments("d").WithLocation(10, 13), // (10,16): warning CS0168: The variable 'e' is declared but never used // int d, e(out var x4); // parsed as a broken bracketed argument list on the declarator Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(10, 16), // (7,13): warning CS8321: The local function 'b' is declared but never used // int b(out var x2) = null; // parsed as a local function with syntax error Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "b").WithArguments("b").WithLocation(7, 13) ); } [Fact] public void ElementAccess_06() { var text = @" public class Cls { public static void Main() { { int[] e = null; var z1 = e?[out var x1]; x1 = 1; } { int[][] e = null; var z2 = e?[out var x2]?[out var x3]; x2 = 1; x3 = 2; } { int[][] e = null; var z3 = e?[0]?[out var x4]; x4 = 1; } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); Assert.True(model.GetTypeInfo(x1Ref).Type.TypeKind == TypeKind.Error); var x2Decl = GetOutVarDeclaration(tree, "x2"); var x2Ref = GetReference(tree, "x2"); Assert.True(model.GetTypeInfo(x2Ref).Type.TypeKind == TypeKind.Error); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); Assert.True(model.GetTypeInfo(x3Ref).Type.TypeKind == TypeKind.Error); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); Assert.True(model.GetTypeInfo(x4Ref).Type.TypeKind == TypeKind.Error); VerifyModelForOutVarWithoutDataFlow(compilation.GetSemanticModel(tree), x1Decl, x1Ref); compilation.VerifyDiagnostics( // (8,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x1").WithArguments("1", "out").WithLocation(8, 29), // (8,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // var z1 = e?[out var x1]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(8, 33), // (13,29): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x2").WithArguments("1", "out").WithLocation(13, 29), // (13,33): error CS8197: Cannot infer the type of implicitly-typed out variable 'x2'. // var z2 = e?[out var x2]?[out var x3]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x2").WithArguments("x2").WithLocation(13, 33), // (19,33): error CS1615: Argument 1 may not be passed with the 'out' keyword // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_BadArgExtraRef, "var x4").WithArguments("1", "out").WithLocation(19, 33), // (19,37): error CS8197: Cannot infer the type of implicitly-typed out variable 'x4'. // var z3 = e?[0]?[out var x4]; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x4").WithArguments("x4").WithLocation(19, 37) ); } [Fact] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[out var x1, x1]; //fixed int F2[3 is int x2 ? x2 : 3]; //fixed int F2[3 is int x3 ? 3 : 3, x3]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.Empty(GetOutVarDeclarations(tree, "x1")); compilation.VerifyDiagnostics( // (4,18): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(4, 18), // (4,26): error CS1003: Syntax error, ',' expected // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(4, 26), // (4,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x1, x1]").WithLocation(4, 17), // (4,22): error CS0103: The name 'var' does not exist in the current context // fixed int F1[out var x1, x1]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(4, 22) ); } [Fact] public void Scope_DeclaratorArguments_01() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { int d,e(Dummy(TakeOutParam(true, out var x1), x1)); } void Test4() { var x4 = 11; Dummy(x4); int d,e(Dummy(TakeOutParam(true, out var x4), x4)); } void Test6() { int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); } void Test8() { int d,e(Dummy(TakeOutParam(true, out var x8), x8)); System.Console.WriteLine(x8); } void Test14() { int d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (19,50): error CS0128: A local variable named 'x4' is already defined in this scope // int d,e(Dummy(TakeOutParam(true, out var x4), x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(19, 50), // (24,23): error CS0841: Cannot use local variable 'x6' before it is declared // int d,e(Dummy(x6 && TakeOutParam(true, out var x6))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(24, 23), // (30,34): error CS0165: Use of unassigned local variable 'x8' // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_UseDefViolation, "x8").WithArguments("x8").WithLocation(30, 34), // (36,47): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(36, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyNotAnOutLocal(model, x4Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").Single(); Assert.Equal(2, x14Decl.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } private static void AssertContainedInDeclaratorArguments(DeclarationExpressionSyntax decl) { Assert.True(decl.Ancestors().OfType<VariableDeclaratorSyntax>().First().ArgumentList.Contains(decl)); } private static void AssertContainedInDeclaratorArguments(params DeclarationExpressionSyntax[] decls) { foreach (var decl in decls) { AssertContainedInDeclaratorArguments(decl); } } [Fact] public void Scope_DeclaratorArguments_02() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { var d, x1( Dummy(TakeOutParam(true, out var x1), x1)); Dummy(x1); } void Test2() { object d, x2( Dummy(TakeOutParam(true, out var x2), x2)); Dummy(x2); } void Test3() { object x3, d( Dummy(TakeOutParam(true, out var x3), x3)); Dummy(x3); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,13): error CS0818: Implicitly-typed variables must be initialized // var d, x1( Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(12, 13), // (13,51): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1), x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 51), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (21,15): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 15), // (27,54): error CS0128: A local variable named 'x3' is already defined in this scope // Dummy(TakeOutParam(true, out var x3), x3)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(27, 54), // (28,15): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(28, 15) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_03() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1( Dummy(x1)); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2)); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2(Dummy(x3)); } void Test4() { object d1,e(Dummy(x4)], d2(Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1( Dummy(x1)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (14,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 15), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1,e(Dummy(x4)], Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_04() { var source = @" public class X { public static void Main() { } object Dummy(params object[] x) {return null;} void Test1() { object d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1); Dummy(x1); } void Test2() { object d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2 = Dummy(TakeOutParam(true, out var x2), x2); } void Test3() { object d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3); } void Test4() { object d1 = Dummy(x4), d2 (Dummy(TakeOutParam(true, out var x4), x4)); } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,16): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 16), // (13,27): error CS0165: Use of unassigned local variable 'x1' // x1 = Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 27), // (20,54): error CS0128: A local variable named 'x2' is already defined in this scope // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 54), // (20,59): error CS0165: Use of unassigned local variable 'x2' // d2 = Dummy(TakeOutParam(true, out var x2), x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(20, 59), // (26,27): error CS0165: Use of unassigned local variable 'x3' // d2 = Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(26, 27), // (31,27): error CS0841: Cannot use local variable 'x4' before it is declared // object d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(31, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_05() { var source = @" public class X { public static void Main() { } long Dummy(params object[] x) {} void Test1() { SpeculateHere(); } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var statement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(@" var y, y1(Dummy(TakeOutParam(true, out var x1), x1)); "); bool success = model.TryGetSpeculativeSemanticModel(GetReferences(tree, "SpeculateHere").Single().SpanStart, statement, out model); Assert.True(success); Assert.NotNull(model); tree = statement.SyntaxTree; var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); Assert.Equal("System.Int32", model.GetTypeInfo(x1Ref[0]).Type.ToTestDisplayString()); var y1 = model.LookupSymbols(x1Ref[0].SpanStart, name: "y1").Single(); Assert.Equal("var y1", y1.ToTestDisplayString()); Assert.True(((ILocalSymbol)y1).Type.IsErrorType()); } [Fact] public void Scope_DeclaratorArguments_06() { var source = @" public class X { public static void Main() { } void Test1() { if (true) var d,e(TakeOutParam(true, out var x1) && x1 != null); x1++; } static bool TakeOutParam(object y, out object x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (11,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var d =TakeOutParam(true, out var x1) && x1 != null; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var d,e(TakeOutParam(true, out var x1) && x1 != null);").WithLocation(11, 13), // (11,17): error CS0818: Implicitly-typed variables must be initialized // var d,e(TakeOutParam(true, out var x1) && x1 != null); Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, "d").WithLocation(11, 17), // (13,9): error CS0103: The name 'x1' does not exist in the current context // x1++; Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(13, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var e = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(id => id.Identifier.ValueText == "e").Single(); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(e); Assert.Equal("var e", symbol.ToTestDisplayString()); Assert.True(symbol.Type.IsErrorType()); } [Fact] [WorkItem(13460, "https://github.com/dotnet/roslyn/issues/13460")] public void Scope_DeclaratorArguments_07() { var source = @" public class X { public static void Main() { Test(1); } static void Test(int val) { switch (val) { case 1 when TakeOutParam(123, out var x1): var z, z1(x1, out var u1, x1 > 0 & TakeOutParam(x1, out var y1)]; System.Console.WriteLine(y1); System.Console.WriteLine(z1 ? 1 : 0); break; } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); AssertContainedInDeclaratorArguments(y1Decl); var yRef = GetReference(tree, "y1"); Assert.Equal("System.Int32", model.GetTypeInfo(yRef).Type.ToTestDisplayString()); model = compilation.GetSemanticModel(tree); var zRef = GetReference(tree, "z1"); Assert.True(((ITypeSymbol)model.GetTypeInfo(zRef).Type).IsErrorType()); } [Fact] [WorkItem(13459, "https://github.com/dotnet/roslyn/issues/13459")] public void Scope_DeclaratorArguments_08() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test1() { for (bool a, b( Dummy(TakeOutParam(true, out var x1) && x1) );;) { Dummy(x1); } } void Test2() { for (bool a, b( Dummy(TakeOutParam(true, out var x2) && x2) );;) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); for (bool a, b( Dummy(TakeOutParam(true, out var x4) && x4) );;) Dummy(x4); } void Test6() { for (bool a, b( Dummy(x6 && TakeOutParam(true, out var x6)) );;) Dummy(x6); } void Test7() { for (bool a, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) { var x7 = 12; Dummy(x7); } } void Test8() { for (bool a, b( Dummy(TakeOutParam(true, out var x8) && x8) );;) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { for (bool a1, b1( Dummy(TakeOutParam(true, out var x9) && x9) );;) { Dummy(x9); for (bool a2, b2( Dummy(TakeOutParam(true, out var x9) && x9) // 2 );;) Dummy(x9); } } void Test10() { for (bool a, b( Dummy(TakeOutParam(y10, out var x10)) );;) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // for (bool a, b( // Dummy(TakeOutParam(y11, out var x11)) // );;) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { for (bool a, b( Dummy(TakeOutParam(y12, out var x12)) );;) var y12 = 12; } //void Test13() //{ // for (bool a, b( // Dummy(TakeOutParam(y13, out var x13)) // );;) // let y13 = 12; //} void Test14() { for (bool a, b( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) );;) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (109,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(109, 13), // (34,47): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(34, 47), // (42,20): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(42, 20), // (53,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(53, 17), // (65,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(65, 34), // (65,9): warning CS0162: Unreachable code detected // System.Console.WriteLine(x8); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(65, 9), // (76,51): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(76, 51), // (85,33): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(85, 33), // (107,33): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(107, 33), // (109,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(109, 17), // (124,44): error CS0128: A local variable named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(124, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_09() { var source = @" public class X { public static void Main() { } bool Dummy(params object[] x) {return true;} void Test4() { for (bool d, x4( Dummy(TakeOutParam(true, out var x4) && x4) );;) {} } void Test7() { for (bool x7 = true, b( Dummy(TakeOutParam(true, out var x7) && x7) );;) {} } void Test8() { for (bool d,b1(Dummy(TakeOutParam(true, out var x8) && x8)], b2(Dummy(TakeOutParam(true, out var x8) && x8)); Dummy(TakeOutParam(true, out var x8) && x8); Dummy(TakeOutParam(true, out var x8) && x8)) {} } void Test9() { for (bool b = x9, b2(Dummy(TakeOutParam(true, out var x9) && x9)); Dummy(TakeOutParam(true, out var x9) && x9); Dummy(TakeOutParam(true, out var x9) && x9)) {} } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,47): error CS0128: A local variable or function named 'x4' is already defined in this scope // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 47), // (21,47): error CS0128: A local variable or function named 'x7' is already defined in this scope // Dummy(TakeOutParam(true, out var x7) && x7) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x7").WithArguments("x7").WithLocation(21, 47), // (20,19): warning CS0219: The variable 'x7' is assigned but its value is never used // for (bool x7 = true, b( Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x7").WithArguments("x7").WithLocation(20, 19), // (29,52): error CS0128: A local variable or function named 'x8' is already defined in this scope // b2(Dummy(TakeOutParam(true, out var x8) && x8)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x8").WithArguments("x8").WithLocation(29, 52), // (30,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(30, 47), // (31,47): error CS0136: A local or parameter named 'x8' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x8) && x8)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x8").WithArguments("x8").WithLocation(31, 47), // (37,23): error CS0841: Cannot use local variable 'x9' before it is declared // for (bool b = x9, Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x9").WithArguments("x9").WithLocation(37, 23), // (39,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(39, 47), // (40,47): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(40, 47) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl); VerifyNotAnOutLocal(model, x4Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").Single(); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarDuplicateInSameScope(model, x7Decl); VerifyNotAnOutLocal(model, x7Ref); var x8Decl = GetOutVarDeclarations(tree, "x8").ToArray(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(4, x8Decl.Length); Assert.Equal(4, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl[0]); AssertContainedInDeclaratorArguments(x8Decl[1]); VerifyModelForOutVarWithoutDataFlow(model, x8Decl[0], x8Ref[0], x8Ref[1]); VerifyModelForOutVarDuplicateInSameScope(model, x8Decl[1]); VerifyModelForOutVar(model, x8Decl[2], x8Ref[2]); VerifyModelForOutVar(model, x8Decl[3], x8Ref[3]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(3, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl[0]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2]); VerifyModelForOutVar(model, x9Decl[2], x9Ref[3]); } [Fact] public void Scope_DeclaratorArguments_10() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,e(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (var d,e(Dummy(TakeOutParam(true, out var x2), x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Dummy(x4); } void Test6() { using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { using (var d,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { using (var d,e(Dummy(TakeOutParam(true, out var x8), x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { using (var d,a(Dummy(TakeOutParam(true, out var x9), x9))) { Dummy(x9); using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Dummy(x9); } } void Test10() { using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // using (var d,e(Dummy(TakeOutParam(y11, out var x11), x11))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) var y12 = 12; } //void Test13() //{ // using (var d,e(Dummy(TakeOutParam(y13, out var x13), x13))) // let y13 = 12; //} void Test14() { using (var d,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,57): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var d,e(Dummy(TakeOutParam(true, out var x4), x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 57), // (35,30): error CS0841: Cannot use local variable 'x6' before it is declared // using (var d,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 30), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,61): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (var e,b(Dummy(TakeOutParam(true, out var x9), x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 61), // (68,43): error CS0103: The name 'y10' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y10, out var x10), x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 43), // (86,43): error CS0103: The name 'y12' does not exist in the current context // using (var d,e(Dummy(TakeOutParam(y12, out var x12), x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 43), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,54): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 54) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); AssertContainedInDeclaratorArguments(x10Decl); VerifyModelForOutVarWithoutDataFlow(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_11() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) { Dummy(x1); } } void Test2() { using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (12,58): error CS0128: A local variable or function named 'x1' is already defined in this scope // using (var d,x1(Dummy(TakeOutParam(true, out var x1), x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(12, 58), // (20,73): error CS0128: A local variable or function named 'x2' is already defined in this scope // using (System.IDisposable d,x2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(20, 73) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); AssertContainedInDeclaratorArguments(x2Decl); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); } [Fact] public void Scope_DeclaratorArguments_12() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(params object[] x) {return null;} void Test1() { using (System.IDisposable d,e(Dummy(TakeOutParam(true, out var x1), x1)], x1 = Dummy(x1)) { Dummy(x1); } } void Test2() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x2), x2)], d2(Dummy(TakeOutParam(true, out var x2), x2))) { Dummy(x2); } } void Test3() { using (System.IDisposable d1,e(Dummy(TakeOutParam(true, out var x3), x3)], d2 = Dummy(x3)) { Dummy(x3); } } void Test4() { using (System.IDisposable d1 = Dummy(x4), d2(Dummy(TakeOutParam(true, out var x4), x4))) { Dummy(x4); } } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (13,35): error CS0128: A local variable named 'x1' is already defined in this scope // x1 = Dummy(x1)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 35), // (22,73): error CS0128: A local variable named 'x2' is already defined in this scope // d2(Dummy(TakeOutParam(true, out var x2), x2))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(22, 73), // (39,46): error CS0841: Cannot use local variable 'x4' before it is declared // using (System.IDisposable d1 = Dummy(x4), Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(39, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(3, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl[0], x2Ref); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl[1]); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref); } [Fact] public void Scope_DeclaratorArguments_13() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} void Test1() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x2) && x2))) Dummy(x2); } void Test4() { var x4 = 11; Dummy(x4); fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Dummy(x4); } void Test6() { fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Dummy(x6); } void Test7() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x7) && x7))) { var x7 = 12; Dummy(x7); } } void Test8() { fixed (int* p,e(Dummy(TakeOutParam(true, out var x8) && x8))) Dummy(x8); System.Console.WriteLine(x8); } void Test9() { fixed (int* p1,a(Dummy(TakeOutParam(true, out var x9) && x9))) { Dummy(x9); fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Dummy(x9); } } void Test10() { fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) { var y10 = 12; Dummy(y10); } } //void Test11() //{ // fixed (int* p,e(Dummy(TakeOutParam(y11, out var x11)))) // { // let y11 = 12; // Dummy(y11); // } //} void Test12() { fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) var y12 = 12; } //void Test13() //{ // fixed (int* p,e(Dummy(TakeOutParam(y13, out var x13)))) // let y13 = 12; //} void Test14() { fixed (int* p,e(Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14))) { Dummy(x14); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (87,13): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(87, 13), // (29,58): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p,e(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(29, 58), // (35,31): error CS0841: Cannot use local variable 'x6' before it is declared // fixed (int* p,e(Dummy(x6 && TakeOutParam(true, out var x6)))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(35, 31), // (43,17): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(43, 17), // (53,34): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(53, 34), // (61,63): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int* p2,b(Dummy(TakeOutParam(true, out var x9) && x9))) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(61, 63), // (68,44): error CS0103: The name 'y10' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y10, out var x10)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(68, 44), // (86,44): error CS0103: The name 'y12' does not exist in the current context // fixed (int* p,e(Dummy(TakeOutParam(y12, out var x12)))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(86, 44), // (87,17): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(87, 17), // (99,55): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(99, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelForOutVarWithoutDataFlow(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelForOutVarWithoutDataFlow(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); AssertContainedInDeclaratorArguments(x8Decl); VerifyModelForOutVarWithoutDataFlow(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); AssertContainedInDeclaratorArguments(x9Decl); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVarWithoutDataFlow(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); AssertContainedInDeclaratorArguments(x14Decl); VerifyModelForOutVarWithoutDataFlow(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } [Fact] public void Scope_DeclaratorArguments_14() { var source = @" public unsafe class X { public static void Main() { } int[] Dummy(params object[] x) {return null;} int[] Dummy(int* x) {return null;} void Test1() { fixed (int* d,x1( Dummy(TakeOutParam(true, out var x1) && x1))) { Dummy(x1); } } void Test2() { fixed (int* d,p(Dummy(TakeOutParam(true, out var x2) && x2)], x2 = Dummy()) { Dummy(x2); } } void Test3() { fixed (int* x3 = Dummy(), p(Dummy(TakeOutParam(true, out var x3) && x3))) { Dummy(x3); } } void Test4() { fixed (int* d,p1(Dummy(TakeOutParam(true, out var x4) && x4)], p2(Dummy(TakeOutParam(true, out var x4) && x4))) { Dummy(x4); } } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, (int)ErrorCode.ERR_SyntaxError, (int)ErrorCode.ERR_UnexpectedToken, (int)ErrorCode.WRN_UnreferencedVar, (int)ErrorCode.ERR_FixedMustInit, (int)ErrorCode.ERR_UseDefViolation, (int)ErrorCode.ERR_CloseParenExpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (14,59): error CS0128: A local variable named 'x1' is already defined in this scope // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(14, 59), // (14,32): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // Dummy(TakeOutParam(true, out var x1) && x1))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x1) && x1").WithArguments("&&", "bool", "int*").WithLocation(14, 32), // (23,21): error CS0128: A local variable named 'x2' is already defined in this scope // x2 = Dummy()) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(23, 21), // (32,58): error CS0128: A local variable named 'x3' is already defined in this scope // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(32, 58), // (32,31): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int*' // p(Dummy(TakeOutParam(true, out var x3) && x3))) Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x3) && x3").WithArguments("&&", "bool", "int*").WithLocation(32, 31), // (41,59): error CS0128: A local variable named 'x4' is already defined in this scope // p2(Dummy(TakeOutParam(true, out var x4) && x4))) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(41, 59) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); VerifyNotAnOutLocal(model, x1Ref[0]); VerifyNotAnOutLocal(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); AssertContainedInDeclaratorArguments(x2Decl); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(2, x3Ref.Length); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelForOutVarDuplicateInSameScope(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyNotAnOutLocal(model, x3Ref[1]); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(2, x4Decl.Length); Assert.Equal(3, x4Ref.Length); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelForOutVarWithoutDataFlow(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } [Fact] public void Scope_DeclaratorArguments_15() { var source = @" public class X { public static void Main() { } bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; bool Test4 [x4 && TakeOutParam(4, out var x4)]; bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (20,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } private static void VerifyModelNotSupported( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { var variableDeclaratorSyntax = GetVariableDesignation(decl); Assert.Null(model.GetDeclaredSymbol(variableDeclaratorSyntax)); Assert.Null(model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax)); var identifierText = decl.Identifier().ValueText; Assert.False(model.LookupSymbols(decl.SpanStart, name: identifierText).Any()); Assert.False(model.LookupNames(decl.SpanStart).Contains(identifierText)); Assert.Null(model.GetSymbolInfo(decl.Type).Symbol); AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: null, expectedType: null); VerifyModelNotSupported(model, references); } private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references) { foreach (var reference in references) { Assert.Null(model.GetSymbolInfo(reference).Symbol); Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any()); Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart)); Assert.True(((ITypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType()); } } [Fact] public void Scope_DeclaratorArguments_16() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; fixed bool Test4 [x4 && TakeOutParam(4, out var x4)]; fixed bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; fixed bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; fixed bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; fixed bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.WRN_UnreferencedField, (int)ErrorCode.ERR_NoImplicitConv }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (10,18): error CS0841: Cannot use local variable 'x4' before it is declared // bool Test4 [x4 && TakeOutParam(4, out var x4)]; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(10, 18), // (13,43): error CS0128: A local variable named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(13, 43), // (20,25): error CS0103: The name 'x7' does not exist in the current context // bool Test72 [Dummy(x7, 2)]; Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(20, 25), // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_17() { var source = @" public class X { public static void Main() { } const bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; const bool Test4 [x4 && TakeOutParam(4, out var x4)]; const bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; const bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; const bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; const bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_18() { var source = @" public class X { public static void Main() { } event bool Test3 [TakeOutParam(3, out var x3) && x3 > 0]; event bool Test4 [x4 && TakeOutParam(4, out var x4)]; event bool Test5 [TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0]; event bool Test61 [TakeOutParam(6, out var x6) && x6 > 0], Test62 [TakeOutParam(6, out var x6) && x6 > 0]; event bool Test71 [TakeOutParam(7, out var x7) && x7 > 0]; event bool Test72 [Dummy(x7, 2)]; void Test73() { Dummy(x7, 3); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(object y, out int x) { x = 123; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_CStyleArray, (int)ErrorCode.ERR_ArraySizeInDeclaration, (int)ErrorCode.ERR_EventNotDelegate, (int)ErrorCode.WRN_UnreferencedEvent }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (21,27): error CS0103: The name 'x7' does not exist in the current context // void Test73() { Dummy(x7, 3); } Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(21, 27) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); AssertContainedInDeclaratorArguments(x4Decl); VerifyModelNotSupported(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); AssertContainedInDeclaratorArguments(x5Decl); VerifyModelNotSupported(model, x5Decl[0], x5Ref); VerifyModelNotSupported(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); AssertContainedInDeclaratorArguments(x6Decl); VerifyModelNotSupported(model, x6Decl[0], x6Ref[0]); VerifyModelNotSupported(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); AssertContainedInDeclaratorArguments(x7Decl); VerifyModelNotSupported(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_DeclaratorArguments_19() { var source = @" public unsafe struct X { public static void Main() { } fixed bool d[2], Test3 (out var x3); } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); int[] exclude = new int[] { (int)ErrorCode.ERR_BadVarDecl, }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (8,28): error CS1003: Syntax error, '[' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(8, 28), // (8,39): error CS1003: Syntax error, ']' expected // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(8, 39), // (8,33): error CS8185: A declaration is not allowed in this context. // fixed bool d[2], Test3 (out var x3); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x3").WithLocation(8, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); AssertContainedInDeclaratorArguments(x3Decl); VerifyModelNotSupported(model, x3Decl); } [Fact] public void Scope_DeclaratorArguments_20() { var source = @" public unsafe struct X { public static void Main() { } fixed bool Test3[out var x3]; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (8,22): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(8, 22), // (8,30): error CS1003: Syntax error, ',' expected // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(8, 30), // (8,21): error CS7092: A fixed buffer may only have one dimension. // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[out var x3]").WithLocation(8, 21), // (8,26): error CS0103: The name 'var' does not exist in the current context // fixed bool Test3[out var x3]; Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 26) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); Assert.False(GetOutVarDeclarations(tree, "x3").Any()); } [Fact] public void StaticType() { var text = @" public class Cls { public static void Main() { Test1(out StaticType x1); } static object Test1(out StaticType x) { throw new System.NotSupportedException(); } static class StaticType {} }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (9,19): error CS0721: 'Cls.StaticType': static types cannot be used as parameters // static object Test1(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "Test1").WithArguments("Cls.StaticType").WithLocation(9, 19), // (6,19): error CS0723: Cannot declare a variable of static type 'Cls.StaticType' // Test1(out StaticType x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("Cls.StaticType").WithLocation(6, 19) ); } [Fact] public void GlobalCode_Catch_01() { var source = @" bool Dummy(params object[] x) {return true;} try {} catch when (TakeOutParam(out var x1) && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,34): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x4) && x4 > 0) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(14, 34), // (20,13): error CS0841: Cannot use local variable 'x6' before it is declared // catch when (x6 && TakeOutParam(out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(20, 13), // (28,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(28, 9), // (38,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(38, 26), // (45,38): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // catch when (TakeOutParam(out var x9) && x9 > 0) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(45, 38), // (52,26): error CS0103: The name 'y10' does not exist in the current context // catch when (TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(52, 26), // (67,42): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(out var x14), // 2 Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(67, 42), // (75,42): error CS0128: A local variable or function named 'x15' is already defined in this scope // when (Dummy(TakeOutParam(out var x15), x15)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "x15").WithArguments("x15").WithLocation(75, 42), // (85,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13), // (85,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(object y, out int x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(85, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclaration(tree, "x6"); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclaration(tree, "x8"); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclaration(tree, "x15"); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x15Decl); VerifyNotAnOutLocal(model, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Catch_02() { var source = @" try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(TakeOutParam(e, out var x1), x1)) { System.Console.WriteLine(x1.GetType()); } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Block_01() { string source = @" { H.TakeOutParam(1, out var x1); H.Dummy(x1); } object x2; { H.TakeOutParam(2, out var x2); H.Dummy(x2); } { H.TakeOutParam(3, out var x3); } H.Dummy(x3); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,8): warning CS0168: The variable 'x2' is declared but never used // object x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(7, 8), // (9,31): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(9, 31), // (15,9): error CS0103: The name 'x3' does not exist in the current context // H.Dummy(x3); Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(15, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotInScope(model, x3Ref); } } [Fact] public void GlobalCode_Block_02() { string source = @" { H.TakeOutParam(1, out var x1); System.Console.WriteLine(x1); Test(); void Test() { System.Console.WriteLine(x1); } } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_For_01() { var source = @" bool Dummy(params object[] x) {return true;} for ( Dummy(TakeOutParam(true, out var x1) && x1) ;;) { Dummy(x1); } for ( // 2 Dummy(TakeOutParam(true, out var x2) && x2) ;;) Dummy(x2); var x4 = 11; Dummy(x4); for ( Dummy(TakeOutParam(true, out var x4) && x4) ;;) Dummy(x4); for ( Dummy(x6 && TakeOutParam(true, out var x6)) ;;) Dummy(x6); for ( Dummy(TakeOutParam(true, out var x7) && x7) ;;) { var x7 = 12; Dummy(x7); } for ( Dummy(TakeOutParam(true, out var x8) && x8) ;;) Dummy(x8); System.Console.WriteLine(x8); for ( Dummy(TakeOutParam(true, out var x9) && x9) ;;) { Dummy(x9); for ( Dummy(TakeOutParam(true, out var x9) && x9) // 2 ;;) Dummy(x9); } for ( Dummy(TakeOutParam(y10, out var x10)) ;;) { var y10 = 12; Dummy(y10); } // for ( // Dummy(TakeOutParam(y11, out var x11)) // ;;) // { // let y11 = 12; // Dummy(y11); // } for ( Dummy(TakeOutParam(y12, out var x12)) ;;) var y12 = 12; // for ( // Dummy(TakeOutParam(y13, out var x13)) // ;;) // let y13 = 12; for ( Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14) ;;) { Dummy(x14); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (20,42): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x4) && x4) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(20, 42), // (74,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(74, 5), // (25,15): error CS0841: Cannot use local variable 'x6' before it is declared // Dummy(x6 && TakeOutParam(true, out var x6)) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(25, 15), // (33,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(33, 9), // (42,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(42, 26), // (50,46): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // Dummy(TakeOutParam(true, out var x9) && x9) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(50, 46), // (56,28): error CS0103: The name 'y10' does not exist in the current context // Dummy(TakeOutParam(y10, out var x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(56, 28), // (72,28): error CS0103: The name 'y12' does not exist in the current context // Dummy(TakeOutParam(y12, out var x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(72, 28), // (83,37): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(83, 37), // (11,1): warning CS0162: Unreachable code detected // for ( // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "for").WithLocation(11, 1), // (74,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(74, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_For_02() { var source = @" bool f = true; for (Dummy(f, TakeOutParam((f ? 10 : 20), out var x0), x0); Dummy(f, TakeOutParam((f ? 1 : 2), out var x1), x1); Dummy(f, TakeOutParam((f ? 100 : 200), out var x2), x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetOutVarDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForOutVar(model, x0Decl, x0Ref); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_Foreach_01() { var source = @"using static Helpers; System.Collections.IEnumerable Dummy(params object[] x) {return null;} foreach (var i in Dummy(TakeOutParam(true, out var x1) && x1)) { Dummy(x1); } foreach (var i in Dummy(TakeOutParam(true, out var x2) && x2)) Dummy(x2); var x4 = 11; Dummy(x4); foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Dummy(x4); foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); foreach (var i in Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } foreach (var i in Dummy(TakeOutParam(true, out var x8) && x8)) Dummy(x8); System.Console.WriteLine(x8); foreach (var i1 in Dummy(TakeOutParam(true, out var x9) && x9)) { Dummy(x9); foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Dummy(x9); } foreach (var i in Dummy(TakeOutParam(y10, out var x10))) { var y10 = 12; Dummy(y10); } // foreach (var i in Dummy(TakeOutParam(y11, out var x11))) // { // let y11 = 12; // Dummy(y11); // } foreach (var i in Dummy(TakeOutParam(y12, out var x12))) var y12 = 12; // foreach (var i in Dummy(TakeOutParam(y13, out var x13))) // let y13 = 12; foreach (var i in Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } foreach (var x15 in Dummy(TakeOutParam(1, out var x15), x15)) { Dummy(x15); } static class Helpers { public static bool TakeOutParam(int y, out int x) { x = y; return true; } public static bool TakeOutParam(bool y, out bool x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,52): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i in Dummy(TakeOutParam(true, out var x4) && x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 52), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,25): error CS0841: Cannot use local variable 'x6' before it is declared // foreach (var i in Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 25), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,57): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var i2 in Dummy(TakeOutParam(true, out var x9) && x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 57), // (39,38): error CS0103: The name 'y10' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y10, out var x10))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 38), // (51,38): error CS0103: The name 'y12' does not exist in the current context // foreach (var i in Dummy(TakeOutParam(y12, out var x12))) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 38), // (58,49): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 49), // (64,14): error CS0136: A local or parameter named 'x15' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // foreach (var x15 in Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x15").WithArguments("x15").WithLocation(64, 14), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); var x15Decl = GetOutVarDeclarations(tree, "x15").Single(); var x15Ref = GetReferences(tree, "x15").ToArray(); Assert.Equal(2, x15Ref.Length); VerifyModelForOutVar(model, x15Decl, x15Ref[0]); VerifyNotAnOutLocal(model, x15Ref[1]); } } [Fact] public void GlobalCode_Foreach_02() { var source = @" bool f = true; foreach (var i in Dummy(TakeOutParam(3, out var x1), x1)) { System.Console.WriteLine(x1); } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_01() { var source = @" bool Dummy(params object[] x) {return true;} Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x3) && x3 > 0)); Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Dummy((System.Func<object, object, bool>) ((o1, o2) => TakeOutParam(o1, out var x5) && TakeOutParam(o2, out var x5) && x5 > 0)); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0), (System.Func<object, bool>) (o => TakeOutParam(o, out var x6) && x6 > 0)); Dummy(x7, 1); Dummy(x7, (System.Func<object, bool>) (o => TakeOutParam(o, out var x7) && x7 > 0), x7); Dummy(x7, 2); Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Dummy(TakeOutParam(true, out var x9), (System.Func<object, bool>) (o => TakeOutParam(o, out var x9) && x9 > 0), x9); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x10) && x10 > 0), TakeOutParam(true, out var x10), x10); var x11 = 11; Dummy(x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x11) && x11 > 0), x11); Dummy((System.Func<object, bool>) (o => TakeOutParam(o, out var x12) && x12 > 0), x12); var x12 = 11; Dummy(x12); static bool TakeOutParam(object y, out int x) { x = 123; return true; } static bool TakeOutParam(bool y, out bool x) { x = true; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutField(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutField(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutField(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,41): error CS0841: Cannot use local variable 'x4' before it is declared // Dummy((System.Func<object, bool>) (o => x4 && TakeOutParam(o, out var x4))); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(6, 41), // (9,82): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(o2, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(9, 82), // (14,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(14, 7), // (15,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 7), // (17,9): error CS0103: The name 'x7' does not exist in the current context // x7); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(17, 9), // (18,7): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 7), // (20,7): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(true, out var x8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 7), // (20,79): error CS0019: Operator '&&' cannot be applied to operands of type 'bool' and 'int' // Dummy(TakeOutParam(true, out var x8) && x8, (System.Func<object, bool>) (o => TakeOutParam(o, out var y8) && x8)); Diagnostic(ErrorCode.ERR_BadBinaryOps, "TakeOutParam(o, out var y8) && x8").WithArguments("&&", "bool", "int").WithLocation(20, 79), // (37,9): error CS0841: Cannot use local variable 'x12' before it is declared // x12); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x12").WithArguments("x12").WithLocation(37, 9), // (47,13): error CS0128: A local variable or function named 'TakeOutParam' is already defined in this scope // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.ERR_LocalDuplicate, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13), // (47,13): warning CS8321: The local function 'TakeOutParam' is declared but never used // static bool TakeOutParam(bool y, out bool x) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(47, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").Single(); VerifyModelForOutVar(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").Single(); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref[0]); VerifyModelForOutVar(model, x6Decl[1], x6Ref[1]); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(5, x7Ref.Length); VerifyNotInScope(model, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyModelForOutVar(model, x7Decl, x7Ref[2]); VerifyNotInScope(model, x7Ref[3]); VerifyNotInScope(model, x7Ref[4]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(2, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(2, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[0]); var x10Decl = GetOutVarDeclarations(tree, "x10").ToArray(); var x10Ref = GetReferences(tree, "x10").ToArray(); Assert.Equal(2, x10Decl.Length); Assert.Equal(2, x10Ref.Length); VerifyModelForOutVar(model, x10Decl[0], x10Ref[0]); VerifyModelForOutVar(model, x10Decl[1], x10Ref[1]); var x11Decl = GetOutVarDeclarations(tree, "x11").Single(); var x11Ref = GetReferences(tree, "x11").ToArray(); Assert.Equal(3, x11Ref.Length); VerifyNotAnOutLocal(model, x11Ref[0]); VerifyModelForOutVar(model, x11Decl, x11Ref[1]); VerifyNotAnOutLocal(model, x11Ref[2]); var x12Decl = GetOutVarDeclarations(tree, "x12").Single(); var x12Ref = GetReferences(tree, "x12").ToArray(); Assert.Equal(3, x12Ref.Length); VerifyModelForOutVar(model, x12Decl, x12Ref[0]); VerifyNotAnOutLocal(model, x12Ref[1]); VerifyNotAnOutLocal(model, x12Ref[2]); } } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void GlobalCode_Lambda_02() { var source = @" System.Func<bool> l = () => TakeOutParam(1, out int x1) && Dummy(x1); System.Console.WriteLine(l()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Lambda_03() { var source = @" System.Console.WriteLine(((System.Func<bool>)(() => TakeOutParam(1, out int x1) && Dummy(x1)))()); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_Query_01() { var source = @" using System.Linq; bool Dummy(params object[] x) {return true;} var r01 = from x in new[] { TakeOutParam(1, out var y1) ? y1 : 0, y1} select x + y1; Dummy(y1); var r02 = from x1 in new[] { TakeOutParam(1, out var y2) ? y2 : 0} from x2 in new[] { TakeOutParam(x1, out var z2) ? z2 : 0, z2, y2} select x1 + x2 + y2 + z2; Dummy(z2); var r03 = from x1 in new[] { TakeOutParam(1, out var y3) ? y3 : 0} let x2 = TakeOutParam(x1, out var z3) && z3 > 0 && y3 < 0 select new { x1, x2, y3, z3}; Dummy(z3); var r04 = from x1 in new[] { TakeOutParam(1, out var y4) ? y4 : 0} join x2 in new[] { TakeOutParam(2, out var z4) ? z4 : 0, z4, y4} on x1 + y4 + z4 + (TakeOutParam(3, out var u4) ? u4 : 0) + v4 equals x2 + y4 + z4 + (TakeOutParam(4, out var v4) ? v4 : 0) + u4 select new { x1, x2, y4, z4, u4, v4 }; Dummy(z4); Dummy(u4); Dummy(v4); var r05 = from x1 in new[] { TakeOutParam(1, out var y5) ? y5 : 0} join x2 in new[] { TakeOutParam(2, out var z5) ? z5 : 0, z5, y5} on x1 + y5 + z5 + (TakeOutParam(3, out var u5) ? u5 : 0) + v5 equals x2 + y5 + z5 + (TakeOutParam(4, out var v5) ? v5 : 0) + u5 into g select new { x1, y5, z5, g, u5, v5 }; Dummy(z5); Dummy(u5); Dummy(v5); var r06 = from x in new[] { TakeOutParam(1, out var y6) ? y6 : 0} where x > y6 && TakeOutParam(1, out var z6) && z6 == 1 select x + y6 + z6; Dummy(z6); var r07 = from x in new[] { TakeOutParam(1, out var y7) ? y7 : 0} orderby x > y7 && TakeOutParam(1, out var z7) && z7 == u7, x > y7 && TakeOutParam(1, out var u7) && u7 == z7 select x + y7 + z7 + u7; Dummy(z7); Dummy(u7); var r08 = from x in new[] { TakeOutParam(1, out var y8) ? y8 : 0} select x > y8 && TakeOutParam(1, out var z8) && z8 == 1; Dummy(z8); var r09 = from x in new[] { TakeOutParam(1, out var y9) ? y9 : 0} group x > y9 && TakeOutParam(1, out var z9) && z9 == u9 by x > y9 && TakeOutParam(1, out var u9) && u9 == z9; Dummy(z9); Dummy(u9); var r10 = from x1 in new[] { TakeOutParam(1, out var y10) ? y10 : 0} from y10 in new[] { 1 } select x1 + y10; var r11 = from x1 in new[] { TakeOutParam(1, out var y11) ? y11 : 0} let y11 = x1 + 1 select x1 + y11; static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutField(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutField(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutField(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutField(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutField(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutField(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutField(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutField(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutField(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutField(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutField(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutField(model, y10Decl, y10Ref[0]); VerifyNotAnOutField(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutField(model, y11Decl, y11Ref[0]); VerifyNotAnOutField(model, y11Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (14,21): error CS0103: The name 'z2' does not exist in the current context // z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(14, 21), // (16,7): error CS0103: The name 'z2' does not exist in the current context // Dummy(z2); Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(16, 7), // (21,25): error CS0103: The name 'z3' does not exist in the current context // z3}; Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(21, 25), // (23,7): error CS0103: The name 'z3' does not exist in the current context // Dummy(z3); Diagnostic(ErrorCode.ERR_NameNotInContext, "z3").WithArguments("z3").WithLocation(23, 7), // (28,29): error CS0103: The name 'v4' does not exist in the current context // v4 Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(28, 29), // (30,29): error CS1938: The name 'u4' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u4 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u4").WithArguments("u4").WithLocation(30, 29), // (32,25): error CS0103: The name 'u4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(32, 25), // (32,29): error CS0103: The name 'v4' does not exist in the current context // u4, v4 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(32, 29), // (35,7): error CS0103: The name 'u4' does not exist in the current context // Dummy(u4); Diagnostic(ErrorCode.ERR_NameNotInContext, "u4").WithArguments("u4").WithLocation(35, 7), // (36,7): error CS0103: The name 'v4' does not exist in the current context // Dummy(v4); Diagnostic(ErrorCode.ERR_NameNotInContext, "v4").WithArguments("v4").WithLocation(36, 7), // (41,29): error CS0103: The name 'v5' does not exist in the current context // v5 Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(41, 29), // (43,29): error CS1938: The name 'u5' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'. // u5 Diagnostic(ErrorCode.ERR_QueryInnerKey, "u5").WithArguments("u5").WithLocation(43, 29), // (46,25): error CS0103: The name 'u5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(46, 25), // (46,29): error CS0103: The name 'v5' does not exist in the current context // u5, v5 }; Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(46, 29), // (49,7): error CS0103: The name 'u5' does not exist in the current context // Dummy(u5); Diagnostic(ErrorCode.ERR_NameNotInContext, "u5").WithArguments("u5").WithLocation(49, 7), // (50,7): error CS0103: The name 'v5' does not exist in the current context // Dummy(v5); Diagnostic(ErrorCode.ERR_NameNotInContext, "v5").WithArguments("v5").WithLocation(50, 7), // (55,21): error CS0103: The name 'z6' does not exist in the current context // z6; Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(55, 21), // (57,7): error CS0103: The name 'z6' does not exist in the current context // Dummy(z6); Diagnostic(ErrorCode.ERR_NameNotInContext, "z6").WithArguments("z6").WithLocation(57, 7), // (61,21): error CS0103: The name 'u7' does not exist in the current context // u7, Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(61, 21), // (63,21): error CS0103: The name 'z7' does not exist in the current context // z7 Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(63, 21), // (65,21): error CS0103: The name 'z7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(65, 21), // (65,26): error CS0103: The name 'u7' does not exist in the current context // z7 + u7; Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(65, 26), // (67,7): error CS0103: The name 'z7' does not exist in the current context // Dummy(z7); Diagnostic(ErrorCode.ERR_NameNotInContext, "z7").WithArguments("z7").WithLocation(67, 7), // (68,7): error CS0103: The name 'u7' does not exist in the current context // Dummy(u7); Diagnostic(ErrorCode.ERR_NameNotInContext, "u7").WithArguments("u7").WithLocation(68, 7), // (73,7): error CS0103: The name 'z8' does not exist in the current context // Dummy(z8); Diagnostic(ErrorCode.ERR_NameNotInContext, "z8").WithArguments("z8").WithLocation(73, 7), // (77,17): error CS0103: The name 'u9' does not exist in the current context // u9 Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(77, 17), // (80,17): error CS0103: The name 'z9' does not exist in the current context // z9; Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(80, 17), // (82,7): error CS0103: The name 'z9' does not exist in the current context // Dummy(z9); Diagnostic(ErrorCode.ERR_NameNotInContext, "z9").WithArguments("z9").WithLocation(82, 7), // (83,7): error CS0103: The name 'u9' does not exist in the current context // Dummy(u9); Diagnostic(ErrorCode.ERR_NameNotInContext, "u9").WithArguments("u9").WithLocation(83, 7), // (86,18): error CS1931: The range variable 'y10' conflicts with a previous declaration of 'y10' // from y10 in new[] { 1 } Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y10").WithArguments("y10").WithLocation(86, 18), // (90,17): error CS1931: The range variable 'y11' conflicts with a previous declaration of 'y11' // let y11 = x1 + 1 Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "y11").WithArguments("y11").WithLocation(90, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var y1Decl = GetOutVarDeclarations(tree, "y1").Single(); var y1Ref = GetReferences(tree, "y1").ToArray(); Assert.Equal(4, y1Ref.Length); VerifyModelForOutVar(model, y1Decl, y1Ref); var y2Decl = GetOutVarDeclarations(tree, "y2").Single(); var y2Ref = GetReferences(tree, "y2").ToArray(); Assert.Equal(3, y2Ref.Length); VerifyModelForOutVar(model, y2Decl, y2Ref); var z2Decl = GetOutVarDeclarations(tree, "z2").Single(); var z2Ref = GetReferences(tree, "z2").ToArray(); Assert.Equal(4, z2Ref.Length); VerifyModelForOutVar(model, z2Decl, z2Ref[0], z2Ref[1]); VerifyNotInScope(model, z2Ref[2]); VerifyNotInScope(model, z2Ref[3]); var y3Decl = GetOutVarDeclarations(tree, "y3").Single(); var y3Ref = GetReferences(tree, "y3").ToArray(); Assert.Equal(3, y3Ref.Length); VerifyModelForOutVar(model, y3Decl, y3Ref); var z3Decl = GetOutVarDeclarations(tree, "z3").Single(); var z3Ref = GetReferences(tree, "z3").ToArray(); Assert.Equal(3, z3Ref.Length); VerifyModelForOutVar(model, z3Decl, z3Ref[0]); VerifyNotInScope(model, z3Ref[1]); VerifyNotInScope(model, z3Ref[2]); var y4Decl = GetOutVarDeclarations(tree, "y4").Single(); var y4Ref = GetReferences(tree, "y4").ToArray(); Assert.Equal(5, y4Ref.Length); VerifyModelForOutVar(model, y4Decl, y4Ref); var z4Decl = GetOutVarDeclarations(tree, "z4").Single(); var z4Ref = GetReferences(tree, "z4").ToArray(); Assert.Equal(6, z4Ref.Length); VerifyModelForOutVar(model, z4Decl, z4Ref); var u4Decl = GetOutVarDeclarations(tree, "u4").Single(); var u4Ref = GetReferences(tree, "u4").ToArray(); Assert.Equal(4, u4Ref.Length); VerifyModelForOutVar(model, u4Decl, u4Ref[0]); VerifyNotInScope(model, u4Ref[1]); VerifyNotInScope(model, u4Ref[2]); VerifyNotInScope(model, u4Ref[3]); var v4Decl = GetOutVarDeclarations(tree, "v4").Single(); var v4Ref = GetReferences(tree, "v4").ToArray(); Assert.Equal(4, v4Ref.Length); VerifyNotInScope(model, v4Ref[0]); VerifyModelForOutVar(model, v4Decl, v4Ref[1]); VerifyNotInScope(model, v4Ref[2]); VerifyNotInScope(model, v4Ref[3]); var y5Decl = GetOutVarDeclarations(tree, "y5").Single(); var y5Ref = GetReferences(tree, "y5").ToArray(); Assert.Equal(5, y5Ref.Length); VerifyModelForOutVar(model, y5Decl, y5Ref); var z5Decl = GetOutVarDeclarations(tree, "z5").Single(); var z5Ref = GetReferences(tree, "z5").ToArray(); Assert.Equal(6, z5Ref.Length); VerifyModelForOutVar(model, z5Decl, z5Ref); var u5Decl = GetOutVarDeclarations(tree, "u5").Single(); var u5Ref = GetReferences(tree, "u5").ToArray(); Assert.Equal(4, u5Ref.Length); VerifyModelForOutVar(model, u5Decl, u5Ref[0]); VerifyNotInScope(model, u5Ref[1]); VerifyNotInScope(model, u5Ref[2]); VerifyNotInScope(model, u5Ref[3]); var v5Decl = GetOutVarDeclarations(tree, "v5").Single(); var v5Ref = GetReferences(tree, "v5").ToArray(); Assert.Equal(4, v5Ref.Length); VerifyNotInScope(model, v5Ref[0]); VerifyModelForOutVar(model, v5Decl, v5Ref[1]); VerifyNotInScope(model, v5Ref[2]); VerifyNotInScope(model, v5Ref[3]); var y6Decl = GetOutVarDeclarations(tree, "y6").Single(); var y6Ref = GetReferences(tree, "y6").ToArray(); Assert.Equal(3, y6Ref.Length); VerifyModelForOutVar(model, y6Decl, y6Ref); var z6Decl = GetOutVarDeclarations(tree, "z6").Single(); var z6Ref = GetReferences(tree, "z6").ToArray(); Assert.Equal(3, z6Ref.Length); VerifyModelForOutVar(model, z6Decl, z6Ref[0]); VerifyNotInScope(model, z6Ref[1]); VerifyNotInScope(model, z6Ref[2]); var y7Decl = GetOutVarDeclarations(tree, "y7").Single(); var y7Ref = GetReferences(tree, "y7").ToArray(); Assert.Equal(4, y7Ref.Length); VerifyModelForOutVar(model, y7Decl, y7Ref); var z7Decl = GetOutVarDeclarations(tree, "z7").Single(); var z7Ref = GetReferences(tree, "z7").ToArray(); Assert.Equal(4, z7Ref.Length); VerifyModelForOutVar(model, z7Decl, z7Ref[0]); VerifyNotInScope(model, z7Ref[1]); VerifyNotInScope(model, z7Ref[2]); VerifyNotInScope(model, z7Ref[3]); var u7Decl = GetOutVarDeclarations(tree, "u7").Single(); var u7Ref = GetReferences(tree, "u7").ToArray(); Assert.Equal(4, u7Ref.Length); VerifyNotInScope(model, u7Ref[0]); VerifyModelForOutVar(model, u7Decl, u7Ref[1]); VerifyNotInScope(model, u7Ref[2]); VerifyNotInScope(model, u7Ref[3]); var y8Decl = GetOutVarDeclarations(tree, "y8").Single(); var y8Ref = GetReferences(tree, "y8").ToArray(); Assert.Equal(2, y8Ref.Length); VerifyModelForOutVar(model, y8Decl, y8Ref); var z8Decl = GetOutVarDeclarations(tree, "z8").Single(); var z8Ref = GetReferences(tree, "z8").ToArray(); Assert.Equal(2, z8Ref.Length); VerifyModelForOutVar(model, z8Decl, z8Ref[0]); VerifyNotInScope(model, z8Ref[1]); var y9Decl = GetOutVarDeclarations(tree, "y9").Single(); var y9Ref = GetReferences(tree, "y9").ToArray(); Assert.Equal(3, y9Ref.Length); VerifyModelForOutVar(model, y9Decl, y9Ref); var z9Decl = GetOutVarDeclarations(tree, "z9").Single(); var z9Ref = GetReferences(tree, "z9").ToArray(); Assert.Equal(3, z9Ref.Length); VerifyModelForOutVar(model, z9Decl, z9Ref[0]); VerifyNotInScope(model, z9Ref[1]); VerifyNotInScope(model, z9Ref[2]); var u9Decl = GetOutVarDeclarations(tree, "u9").Single(); var u9Ref = GetReferences(tree, "u9").ToArray(); Assert.Equal(3, u9Ref.Length); VerifyNotInScope(model, u9Ref[0]); VerifyModelForOutVar(model, u9Decl, u9Ref[1]); VerifyNotInScope(model, u9Ref[2]); var y10Decl = GetOutVarDeclarations(tree, "y10").Single(); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyModelForOutVar(model, y10Decl, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y11Decl = GetOutVarDeclarations(tree, "y11").Single(); var y11Ref = GetReferences(tree, "y11").ToArray(); Assert.Equal(2, y11Ref.Length); VerifyModelForOutVar(model, y11Decl, y11Ref[0]); VerifyNotAnOutLocal(model, y11Ref[1]); } } [Fact] public void GlobalCode_Query_02() { var source = @" using System.Linq; var res = from x1 in new[] { TakeOutParam(1, out var y1) && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } static bool Print(object x) { System.Console.WriteLine(x); return true; } "; var compilation = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetOutVarDeclarations(tree, "y1").Single(); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForOutField(model, yDecl, yRef); } [Fact] public void GlobalCode_Using_01() { var source = @" System.IDisposable Dummy(params object[] x) {return null;} using (Dummy(TakeOutParam(true, out var x1), x1)) { Dummy(x1); } using (Dummy(TakeOutParam(true, out var x2), x2)) Dummy(x2); var x4 = 11; Dummy(x4); using (Dummy(TakeOutParam(true, out var x4), x4)) Dummy(x4); using (Dummy(x6 && TakeOutParam(true, out var x6))) Dummy(x6); using (Dummy(TakeOutParam(true, out var x7) && x7)) { var x7 = 12; Dummy(x7); } using (Dummy(TakeOutParam(true, out var x8), x8)) Dummy(x8); System.Console.WriteLine(x8); using (Dummy(TakeOutParam(true, out var x9), x9)) { Dummy(x9); using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Dummy(x9); } using (Dummy(TakeOutParam(y10, out var x10), x10)) { var y10 = 12; Dummy(y10); } // using (Dummy(TakeOutParam(y11, out var x11), x11)) // { // let y11 = 12; // Dummy(y11); // } using (Dummy(TakeOutParam(y12, out var x12), x12)) var y12 = 12; // using (Dummy(TakeOutParam(y13, out var x13), x13)) // let y13 = 12; using (Dummy(TakeOutParam(1, out var x14), TakeOutParam(2, out var x14), x14)) { Dummy(x14); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (15,41): error CS0136: A local or parameter named 'x4' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x4), x4)) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x4").WithArguments("x4").WithLocation(15, 41), // (18,14): error CS0841: Cannot use local variable 'x6' before it is declared // using (Dummy(x6 && TakeOutParam(true, out var x6))) Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x6").WithArguments("x6").WithLocation(18, 14), // (23,9): error CS0136: A local or parameter named 'x7' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // var x7 = 12; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x7").WithArguments("x7").WithLocation(23, 9), // (30,26): error CS0103: The name 'x8' does not exist in the current context // System.Console.WriteLine(x8); Diagnostic(ErrorCode.ERR_NameNotInContext, "x8").WithArguments("x8").WithLocation(30, 26), // (35,45): error CS0136: A local or parameter named 'x9' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (Dummy(TakeOutParam(true, out var x9), x9)) // 2 Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x9").WithArguments("x9").WithLocation(35, 45), // (39,27): error CS0103: The name 'y10' does not exist in the current context // using (Dummy(TakeOutParam(y10, out var x10), x10)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y10").WithArguments("y10").WithLocation(39, 27), // (51,27): error CS0103: The name 'y12' does not exist in the current context // using (Dummy(TakeOutParam(y12, out var x12), x12)) Diagnostic(ErrorCode.ERR_NameNotInContext, "y12").WithArguments("y12").WithLocation(51, 27), // (52,5): error CS1023: Embedded statement cannot be a declaration or labeled statement // var y12 = 12; Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "var y12 = 12;").WithLocation(52, 5), // (52,9): warning CS0219: The variable 'y12' is assigned but its value is never used // var y12 = 12; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y12").WithArguments("y12").WithLocation(52, 9), // (58,41): error CS0128: A local variable or function named 'x14' is already defined in this scope // TakeOutParam(2, out var x14), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x14").WithArguments("x14").WithLocation(58, 41) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl, x2Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").Single(); var x4Ref = GetReferences(tree, "x4").ToArray(); Assert.Equal(3, x4Ref.Length); VerifyNotAnOutLocal(model, x4Ref[0]); VerifyModelForOutVar(model, x4Decl, x4Ref[1], x4Ref[2]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVar(model, x6Decl, x6Ref); var x7Decl = GetOutVarDeclarations(tree, "x7").Single(); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(2, x7Ref.Length); VerifyModelForOutVar(model, x7Decl, x7Ref[0]); VerifyNotAnOutLocal(model, x7Ref[1]); var x8Decl = GetOutVarDeclarations(tree, "x8").Single(); var x8Ref = GetReferences(tree, "x8").ToArray(); Assert.Equal(3, x8Ref.Length); VerifyModelForOutVar(model, x8Decl, x8Ref[0], x8Ref[1]); VerifyNotInScope(model, x8Ref[2]); var x9Decl = GetOutVarDeclarations(tree, "x9").ToArray(); var x9Ref = GetReferences(tree, "x9").ToArray(); Assert.Equal(2, x9Decl.Length); Assert.Equal(4, x9Ref.Length); VerifyModelForOutVar(model, x9Decl[0], x9Ref[0], x9Ref[1]); VerifyModelForOutVar(model, x9Decl[1], x9Ref[2], x9Ref[3]); var x10Decl = GetOutVarDeclarations(tree, "x10").Single(); var x10Ref = GetReferences(tree, "x10").Single(); VerifyModelForOutVar(model, x10Decl, x10Ref); var y10Ref = GetReferences(tree, "y10").ToArray(); Assert.Equal(2, y10Ref.Length); VerifyNotInScope(model, y10Ref[0]); VerifyNotAnOutLocal(model, y10Ref[1]); var y12Ref = GetReferences(tree, "y12").Single(); VerifyNotInScope(model, y12Ref); var x14Decl = GetOutVarDeclarations(tree, "x14").ToArray(); var x14Ref = GetReferences(tree, "x14").ToArray(); Assert.Equal(2, x14Decl.Length); Assert.Equal(2, x14Ref.Length); VerifyModelForOutVar(model, x14Decl[0], x14Ref); VerifyModelForOutVarDuplicateInSameScope(model, x14Decl[1]); } } [Fact] public void GlobalCode_Using_02() { var source = @" using (System.IDisposable d1 = Dummy(new C(""a""), TakeOutParam(new C(""b""), out var x1)), d2 = Dummy(new C(""c""), TakeOutParam(new C(""d""), out var x2))) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), TakeOutParam(new C(""f""), out var x1))) { System.Console.WriteLine(x1); } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void GlobalCode_ExpressionStatement_01() { string source = @" H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out int x2); H.TakeOutParam(3, out int x3); object x3; H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } private static void AssertNoGlobalStatements(SyntaxTree tree) { Assert.Empty(tree.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()); } [Fact] public void GlobalCode_ExpressionStatement_02() { string source = @" H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; H.TakeOutParam(2, out var x2); H.TakeOutParam(3, out var x3); object x3; H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); Test(); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,27): error CS0102: The type 'Script' already contains a definition for 'x2' // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 27), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,36): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 36), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,27): error CS0128: A local variable or function named 'x2' is already defined in this scope // H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 27), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,36): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 36), // (13,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(13, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ExpressionStatement_03() { string source = @" System.Console.WriteLine(x1); H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_IfStatement_01() { string source = @" if (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out int x2)) {} if (H.TakeOutParam(3, out int x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} if (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); int x6 = 6; if (H.Dummy()) { string x6 = ""6""; H.Dummy(x6); } void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (30,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(30, 17), // (30,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(30, 21), // (30,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(30, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (21,5): warning CS0219: The variable 'x6' is assigned but its value is never used // int x6 = 6; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x6").WithArguments("x6").WithLocation(21, 5), // (24,12): error CS0136: A local or parameter named 'x6' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string x6 = "6"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x6").WithArguments("x6").WithLocation(24, 12), // (33,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(33, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_IfStatement_02() { string source = @" if (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; if (H.TakeOutParam(2, out var x2)) {} if (H.TakeOutParam(3, out var x3)) {} object x3; if (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} void Test() { H.Dummy(x1, x2, x3, x4, x5); } if (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,31): error CS0102: The type 'Script' already contains a definition for 'x2' // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 31), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,40): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 40), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,31): error CS0128: A local variable or function named 'x2' is already defined in this scope // if (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 31), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,40): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 40), // (16,29): error CS0841: Cannot use local variable 'x5' before it is declared // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x5").WithArguments("x5").WithLocation(16, 29), // (21,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(21, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[1]); } } [Fact] public void GlobalCode_IfStatement_03() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_IfStatement_04() { string source = @" System.Console.WriteLine(x1); if (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_YieldReturnStatement_01() { string source = @" yield return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out int x2); yield return H.TakeOutParam(3, out int x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out int x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_YieldReturnStatement_02() { string source = @" yield return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; yield return H.TakeOutParam(2, out var x2); yield return H.TakeOutParam(3, out var x3); object x3; yield return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,40): error CS0102: The type 'Script' already contains a definition for 'x2' // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 40), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,49): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 49), // (2,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(2, 1), // (6,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(6, 1), // (8,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(8, 1), // (11,1): error CS7020: Cannot use 'yield' in top-level script code // yield return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_YieldNotAllowedInScript, "yield").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield return H.TakeOutParam(1, out var x1);").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(2, 1), // (6,40): error CS0128: A local variable or function named 'x2' is already defined in this scope // yield return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 40), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_01() { string source = @" return H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out int x2); return H.TakeOutParam(3, out int x3); object x3; return H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out int x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out int x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out int x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_02() { string source = @" return H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; return H.TakeOutParam(2, out var x2); return H.TakeOutParam(3, out var x3); object x3; return H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,34): error CS0102: The type 'Script' already contains a definition for 'x2' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 34), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,43): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 43), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(1, out var x1)").WithArguments("bool", "int").WithLocation(2, 8), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(2, out var x2)").WithArguments("bool", "int").WithLocation(6, 8), // (6,34): error CS0128: A local variable or function named 'x2' is already defined in this scope // return H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 34), // (8,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NoImplicitConv, "H.TakeOutParam(3, out var x3)").WithArguments("bool", "int").WithLocation(8, 8), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,8): error CS0029: Cannot implicitly convert type 'bool' to 'int' // return H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NoImplicitConv, @"H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))").WithArguments("bool", "int").WithLocation(11, 8), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (14,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(14, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ReturnStatement_03() { string source = @" System.Console.WriteLine(x1); Test(); return H.Dummy(H.TakeOutParam(1, out var x1), x1); void Test() { System.Console.WriteLine(x1); } class H { public static bool Dummy(object x, object y) { System.Console.WriteLine(y); return true; } public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_ThrowStatement_01() { string source = @" throw H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out int x2); throw H.TakeOutParam(3, out int x3); object x3; throw H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_ThrowStatement_02() { string source = @" throw H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; throw H.TakeOutParam(2, out var x2); throw H.TakeOutParam(3, out var x3); object x3; throw H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static System.Exception Dummy(params object[] x) {return null;} public static System.Exception TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); Assert.Equal("System.Int32", ((IFieldSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl.VariableDesignation())).Type.ToTestDisplayString()); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,1): warning CS0162: Unreachable code detected // H.Dummy(x1); Diagnostic(ErrorCode.WRN_UnreachableCode, "H").WithLocation(3, 1), // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // throw H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_SwitchStatement_01() { string source = @" switch (H.TakeOutParam(1, out int x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out int x2)) {default: break;} switch (H.TakeOutParam(3, out int x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {default: break;} switch (H.TakeOutParam(51, out int x5)) { default: H.TakeOutParam(""52"", out string x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out int x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 37), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_02() { string source = @" switch (H.TakeOutParam(1, out var x1)) {default: break;} H.Dummy(x1); object x2; switch (H.TakeOutParam(2, out var x2)) {default: break;} switch (H.TakeOutParam(3, out var x3)) {default: break;} object x3; switch (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {default: break;} switch (H.TakeOutParam(51, out var x5)) { default: H.TakeOutParam(""52"", out var x5); H.Dummy(x5); break; } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,35): error CS0102: The type 'Script' already contains a definition for 'x2' // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 35), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,44): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 44), // (25,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(25, 17), // (25,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(25, 21), // (25,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(25, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,35): error CS0128: A local variable or function named 'x2' is already defined in this scope // switch (H.TakeOutParam(2, out var x2)) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 35), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (12,44): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {default: break;} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 44), // (17,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(17, 34), // (28,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(28, 1), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_SwitchStatement_03() { string source = @" System.Console.WriteLine(x1); switch (H.TakeOutParam(1, out var x1)) { default: H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); break; } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_WhileStatement_01() { string source = @" while (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out int x2)) {} while (H.TakeOutParam(3, out int x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} while (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out int x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_02() { string source = @" while (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; while (H.TakeOutParam(2, out var x2)) {} while (H.TakeOutParam(3, out var x3)) {} object x3; while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} while (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,34): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 34), // (8,34): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // while (H.TakeOutParam(3, out var x3)) {} Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 34), // (12,43): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 43), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (19,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(19, 9), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_WhileStatement_03() { string source = @" while (H.TakeOutParam(1, out var x1)) { System.Console.WriteLine(x1); break; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_DoStatement_01() { string source = @" do {} while (H.TakeOutParam(1, out int x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out int x2)); do {} while (H.TakeOutParam(3, out int x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))); do { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } while (H.TakeOutParam(51, out int x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out int x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out int x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_02() { string source = @" do {} while (H.TakeOutParam(1, out var x1)); H.Dummy(x1); object x2; do {} while (H.TakeOutParam(2, out var x2)); do {} while (H.TakeOutParam(3, out var x3)); object x3; do {} while (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))); do { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } while (H.TakeOutParam(51, out var x5)); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(3, 9), // (6,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(2, out var x2)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(6, 40), // (8,40): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // do {} while (H.TakeOutParam(3, out var x3)); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(8, 40), // (12,49): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 49), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (20,9): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 9), // (22,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(22, 6), // (24,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(24, 13), // (24,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(24, 25), // (24,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(24, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[0]); VerifyModelForOutVar(model, x5Decl[1]); VerifyNotInScope(model, x5Ref[1]); VerifyNotInScope(model, x5Ref[2]); } } [Fact] public void GlobalCode_DoStatement_03() { string source = @" int f = 1; do { } while (H.TakeOutParam(f++, out var x1) && Test(x1) < 3); int Test(int x) { System.Console.WriteLine(x); return x; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"1 2 3").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForOutVar(model, x1Decl[0], x1Ref); } [Fact] public void GlobalCode_LockStatement_01() { string source = @" lock (H.TakeOutParam(1, out int x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out int x2)) {} lock (H.TakeOutParam(3, out int x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4))) {} lock (H.TakeOutParam(51, out int x5)) { H.TakeOutParam(""52"", out string x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out int x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,37): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out string x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 37), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_02() { string source = @" lock (H.TakeOutParam(1, out var x1)) {} H.Dummy(x1); object x2; lock (H.TakeOutParam(2, out var x2)) {} lock (H.TakeOutParam(3, out var x3)) {} object x3; lock (H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4))) {} lock (H.TakeOutParam(51, out var x5)) { H.TakeOutParam(""52"", out var x5); H.Dummy(x5); } H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static object Dummy(params object[] x) {return true;} public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,33): error CS0102: The type 'Script' already contains a definition for 'x2' // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 33), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,42): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 42), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutField(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,33): error CS0128: A local variable or function named 'x2' is already defined in this scope // lock (H.TakeOutParam(2, out var x2)) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 33), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,42): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4))) {} Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 42), // (16,34): error CS0136: A local or parameter named 'x5' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // H.TakeOutParam("52", out var x5); Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x5").WithArguments("x5").WithLocation(16, 34), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Decl.Length); Assert.Equal(3, x5Ref.Length); VerifyModelForOutVar(model, x5Decl[0], x5Ref[1], x5Ref[2]); VerifyModelForOutVar(model, x5Decl[1], x5Ref[0]); } } [Fact] public void GlobalCode_LockStatement_03() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) { H.TakeOutParam(""11"", out var x1); System.Console.WriteLine(x1); } Test(); void Test() { System.Console.WriteLine(x1); } class H { public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] public void GlobalCode_LockStatement_04() { string source = @" System.Console.WriteLine(x1); lock (H.TakeOutParam(1, out var x1)) H.Dummy(H.TakeOutParam(""11"", out var x1), x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static void Dummy(object x, object y) { System.Console.WriteLine(y); } public static object TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 11 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForOutField(model, x1Decl[0], x1Ref[0], x1Ref[2]); VerifyModelForOutVar(model, x1Decl[1], x1Ref[1]); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_DeconstructionDeclarationStatement_01() { string source = @" (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); Test(); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref[0]); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (16,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(16, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref[0]); } } [Fact] public void GlobalCode_LabeledStatement_01() { string source = @" a: H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out int x2); c: H.TakeOutParam(3, out int x3); object x3; d: H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_02() { string source = @" a: H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; b: H.TakeOutParam(2, out var x2); c: H.TakeOutParam(3, out var x3); object x3; d: H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); void Test() { H.Dummy(x1, x2, x3, x4); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,30): error CS0102: The type 'Script' already contains a definition for 'x2' // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 30), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,39): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 39), // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (16,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(16, 17), // (16,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(16, 21), // (16,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(16, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(6, 1), // (6,30): error CS0128: A local variable or function named 'x2' is already defined in this scope // b: H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 30), // (8,1): warning CS0164: This label has not been referenced // c: H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(8, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (11,1): warning CS0164: This label has not been referenced // d: H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(11, 1), // (12,39): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 39), // (19,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(19, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); } } [Fact] public void GlobalCode_LabeledStatement_03() { string source = @" System.Console.WriteLine(x1); a:b:c:H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c:H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_04() { string source = @" a: bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out int x2); e: bool f = H.TakeOutParam(3, out int x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); i: bool x5 = H.TakeOutParam(5, out int x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [Fact] public void GlobalCode_LabeledStatement_05() { string source = @" a: bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; c: bool d = H.TakeOutParam(2, out var x2); e: bool f = H.TakeOutParam(3, out var x3); object x3; g: bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); i: bool x5 = H.TakeOutParam(5, out var x5); H.Dummy(x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutField(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (2,1): warning CS0164: This label has not been referenced // a: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(2, 1), // (6,1): warning CS0164: This label has not been referenced // c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(6, 1), // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (8,1): warning CS0164: This label has not been referenced // e: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "e").WithLocation(8, 1), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (11,1): warning CS0164: This label has not been referenced // g: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "g").WithLocation(11, 1), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (14,1): warning CS0164: This label has not been referenced // i: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "i").WithLocation(14, 1), // (15,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // bool x5 = H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(15, 37), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(2, x5Ref.Length); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref[0]); VerifyNotAnOutLocal(model, x5Ref[1]); } } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void GlobalCode_LabeledStatement_06_Script() { string source = @" System.Console.WriteLine(x1); a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_LabeledStatement_06_SimpleProgram() { string source = @" a:b:c: var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, expectedOutput: @"1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutVar(model, x1Decl, x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_07() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out int x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out int x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), H.TakeOutParam(6, out int x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out int x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out int x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out int x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_08() { string source = @"l1: (bool a, int b) = (H.TakeOutParam(1, out var x1), 1); H.Dummy(x1); object x2; l2: (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); l3: (bool e, int f) = (H.TakeOutParam(3, out var x3), 3); object x3; l4: (bool g, bool h) = (H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); l5: (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), H.TakeOutParam(6, out var x6)); void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (6,46): error CS0102: The type 'Script' already contains a definition for 'x2' // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(6, 46), // (9,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(9, 8), // (12,48): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(12, 48), // (14,49): error CS0102: The type 'Script' already contains a definition for 'x5' // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(14, 49), // (15,49): error CS0102: The type 'Script' already contains a definition for 'x6' // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(15, 49), // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (19,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(19, 17), // (19,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(19, 21), // (19,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(19, 25), // (19,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(19, 29), // (19,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(19, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").ToArray(); Assert.Equal(1, x5Ref.Length); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(1, x6Ref.Length); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (1,1): warning CS0164: This label has not been referenced // l1: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l1").WithLocation(1, 1), // (5,1): warning CS0164: This label has not been referenced // l2: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l2").WithLocation(5, 1), // (6,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // (bool c, int d) = (H.TakeOutParam(2, out var x2), 2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(6, 46), // (7,1): warning CS0164: This label has not been referenced // l3: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l3").WithLocation(7, 1), // (9,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(9, 8), // (9,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(9, 8), // (10,1): warning CS0164: This label has not been referenced // l4: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l4").WithLocation(10, 1), // (12,48): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(12, 48), // (13,1): warning CS0164: This label has not been referenced // l5: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "l5").WithLocation(13, 1), // (14,49): error CS0128: A local variable or function named 'x5' is already defined in this scope // (bool x5, bool x6) = (H.TakeOutParam(5, out var x5), Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(14, 49), // (15,49): error CS0128: A local variable or function named 'x6' is already defined in this scope // H.TakeOutParam(6, out var x6)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(15, 49), // (22,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(22, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl); VerifyNotAnOutLocal(model, x6Ref); } } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void GlobalCode_LabeledStatement_09() { string source = @" System.Console.WriteLine(x1); a:b:c: var (d, e) = (H.TakeOutParam(1, out var x1), 1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, references: new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics( // (3,1): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(3, 1), // (3,3): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "b").WithLocation(3, 3), // (3,5): warning CS0164: This label has not been referenced // a:b:c: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "c").WithLocation(3, 5) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_01() { string source = @" bool b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out int x2); bool f = H.TakeOutParam(3, out int x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 = H.TakeOutParam(5, out int x5); bool i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_02() { string source = @" bool b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d = H.TakeOutParam(2, out var x2); bool f = H.TakeOutParam(3, out var x3); object x3; bool h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 = H.TakeOutParam(5, out var x5); bool i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,36): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 36), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,45): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 45), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (7,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // bool d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(7, 36), // (10,8): error CS0128: A local variable or function named 'x3' is already defined in this scope // object x3; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x3").WithArguments("x3").WithLocation(10, 8), // (10,8): warning CS0168: The variable 'x3' is declared but never used // object x3; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x3").WithArguments("x3").WithLocation(10, 8), // (13,45): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 45), // (16,37): error CS0128: A local variable or function named 'x5' is already defined in this scope // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(16, 37), // (19,10): error CS0128: A local variable or function named 'x6' is already defined in this scope // x6; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(19, 10), // (19,10): warning CS0168: The variable 'x6' is declared but never used // x6; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x6").WithArguments("x6").WithLocation(19, 10), // (26,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(26, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0], x4Ref); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl); VerifyNotAnOutLocal(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl, x6Ref); } } [Fact] public void GlobalCode_FieldDeclaration_03() { string source = @" System.Console.WriteLine(x1); var d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static var b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_05() { string source = @" bool b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_06() { string source = @" bool b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_FieldDeclaration_07() { string source = @" Test(); bool a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); bool Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return false; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_PropertyDeclaration_01() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out int x2); bool f { get; } = H.TakeOutParam(3, out int x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); bool x5 { get; } = H.TakeOutParam(5, out int x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out int x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out int x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out int x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_02() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; bool d { get; } = H.TakeOutParam(2, out var x2); bool f { get; } = H.TakeOutParam(3, out var x3); object x3; bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); bool x5 { get; } = H.TakeOutParam(5, out var x5); void Test() { H.Dummy(x1, x2, x3, x4, x5); } Test(); class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,45): error CS0102: The type 'Script' already contains a definition for 'x2' // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 45), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,54): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 54), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (20,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(20, 17), // (20,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(20, 21), // (20,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(20, 25), // (20,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(20, 29) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool b { get; } = H.TakeOutParam(1, out var x1); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(3, 6), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (7,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool d { get; } = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(7, 6), // (9,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool f { get; } = H.TakeOutParam(3, out var x3); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "f").WithLocation(9, 6), // (12,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool h { get; } = H.Dummy(H.TakeOutParam(41, out var x4), Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "h").WithLocation(12, 6), // (13,54): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 54), // (15,6): error CS0116: A namespace cannot directly contain members such as fields or methods // bool x5 { get; } = Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "x5").WithLocation(15, 6), // (20,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(20, 13), // (20,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(20, 25), // (20,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(20, 29), // (23,1): error CS0165: Use of unassigned local variable 'x2' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x2").WithLocation(23, 1), // (23,1): error CS0165: Use of unassigned local variable 'x3' // Test(); Diagnostic(ErrorCode.ERR_UseDefViolation, "Test()").WithArguments("x3").WithLocation(23, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); } } [Fact] public void GlobalCode_PropertyDeclaration_03() { string source = @" System.Console.WriteLine(x1); bool d { get; set; } = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static bool b { get; } = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_05() { string source = @" bool b { get; } = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_PropertyDeclaration_06() { string source = @" bool b { get; } = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_01() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out int x2); event System.Action f = H.TakeOutParam(3, out int x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out int x4), H.TakeOutParam(42, out int x4)); event System.Action x5 = H.TakeOutParam(5, out int x5); event System.Action i = H.TakeOutParam(5, out int x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out int x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out int x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out int x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_02() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); H.Dummy(x1); object x2; event System.Action d = H.TakeOutParam(2, out var x2); event System.Action f = H.TakeOutParam(3, out var x3); object x3; event System.Action h = H.Dummy(H.TakeOutParam(41, out var x4), H.TakeOutParam(42, out var x4)); event System.Action x5 = H.TakeOutParam(5, out var x5); event System.Action i = H.TakeOutParam(5, out var x6), x6; void Test() { H.Dummy(x1, x2, x3, x4, x5, x6); } class H { public static System.Action Dummy(params object[] x) {return null;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (7,51): error CS0102: The type 'Script' already contains a definition for 'x2' // event System.Action d = H.TakeOutParam(2, out var x2); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x2").WithArguments("Script", "x2").WithLocation(7, 51), // (10,8): error CS0102: The type 'Script' already contains a definition for 'x3' // object x3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x3").WithArguments("Script", "x3").WithLocation(10, 8), // (13,52): error CS0102: The type 'Script' already contains a definition for 'x4' // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x4").WithArguments("Script", "x4").WithLocation(13, 52), // (16,37): error CS0102: The type 'Script' already contains a definition for 'x5' // H.TakeOutParam(5, out var x5); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x5").WithArguments("Script", "x5").WithLocation(16, 37), // (19,10): error CS0102: The type 'Script' already contains a definition for 'x6' // x6; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x6").WithArguments("Script", "x6").WithLocation(19, 10), // (23,17): error CS0229: Ambiguity between 'x2' and 'x2' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x2").WithArguments("x2", "x2").WithLocation(23, 17), // (23,21): error CS0229: Ambiguity between 'x3' and 'x3' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x3").WithArguments("x3", "x3").WithLocation(23, 21), // (23,25): error CS0229: Ambiguity between 'x4' and 'x4' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x4").WithArguments("x4", "x4").WithLocation(23, 25), // (23,29): error CS0229: Ambiguity between 'x5' and 'x5' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x5").WithArguments("x5", "x5").WithLocation(23, 29), // (23,33): error CS0229: Ambiguity between 'x6' and 'x6' // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_AmbigMember, "x6").WithArguments("x6", "x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutFieldDuplicate(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutFieldDuplicate(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutFieldDuplicate(model, x4Decl[0], x4Ref); VerifyModelForOutFieldDuplicate(model, x4Decl[1], x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutFieldDuplicate(model, x5Decl, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutFieldDuplicate(model, x6Decl, x6Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); int[] exclude = new int[] { (int)ErrorCode.ERR_NamespaceUnexpected }; compilation.GetDiagnostics().Where(d => !exclude.Contains(d.Code)).Verify( // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (13,52): error CS0128: A local variable or function named 'x4' is already defined in this scope // H.TakeOutParam(42, out var x4)); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x4").WithArguments("x4").WithLocation(13, 52), // (21,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(21, 6), // (23,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(23, 13), // (23,25): error CS0103: The name 'x4' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(23, 25), // (23,29): error CS0103: The name 'x5' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(23, 29), // (23,33): error CS0103: The name 'x6' does not exist in the current context // H.Dummy(x1, x2, x3, x4, x5, x6); Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(23, 33) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVar(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVar(model, x2Decl); VerifyNotAnOutLocal(model, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").Single(); VerifyModelForOutVar(model, x3Decl); VerifyNotAnOutLocal(model, x3Ref); var x4Decl = GetOutVarDeclarations(tree, "x4").ToArray(); var x4Ref = GetReferences(tree, "x4").Single(); Assert.Equal(2, x4Decl.Length); VerifyModelForOutVar(model, x4Decl[0]); VerifyModelForOutVarDuplicateInSameScope(model, x4Decl[1]); VerifyNotInScope(model, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").Single(); var x5Ref = GetReferences(tree, "x5").Single(); VerifyModelForOutVar(model, x5Decl); VerifyNotInScope(model, x5Ref); var x6Decl = GetOutVarDeclarations(tree, "x6").Single(); var x6Ref = GetReferences(tree, "x6").Single(); VerifyModelForOutVar(model, x6Decl); VerifyNotInScope(model, x6Ref); } } [Fact] public void GlobalCode_EventDeclaration_03() { string source = @" System.Console.WriteLine(x1); event System.Action d = H.TakeOutParam(1, out var x1); Test(); void Test() { System.Console.WriteLine(x1); } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_04() { string source = @" static var a = InitA(); System.Console.WriteLine(x1); static event System.Action b = H.TakeOutParam(1, out var x1); Test(); static var c = InitB(); void Test() { System.Console.WriteLine(x1); } static object InitA() { System.Console.WriteLine(""InitA {0}"", x1); return null; } static object InitB() { System.Console.WriteLine(""InitB {0}"", x1); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"InitA 0 InitB 1 1 1").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(4, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_05() { string source = @" event System.Action b = H.TakeOutParam(1, out var x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_06() { string source = @" event System.Action b = H.TakeOutParam(1, out int x1); static var d = x1; static void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,16): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // static var d = x1; Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(4, 16), // (8,13): error CS0120: An object reference is required for the non-static field, method, or property 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_ObjectRequired, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_EventDeclaration_07() { string source = @" Test(); event System.Action a = H.TakeOutParam(1, out var x1), b = Test(), c = H.TakeOutParam(2, out var x2); Test(); System.Action Test() { System.Console.WriteLine(""{0} {1}"", x1, x2); return null; } class H { public static System.Action TakeOutParam<T>(T y, out T x) { x = y; return null; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); CompileAndVerify(compilation, expectedOutput: @"0 0 1 0 1 2").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl, x2Ref); } [Fact] public void GlobalCode_DeclaratorArguments_01() { string source = @" bool a, b(out var x1); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,19): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(3, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_BadVarDecl, "(out var x1").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,21): error CS1003: Syntax error, ']' expected // bool a, b(out var x1); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 21), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(out var x1); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_02() { string source = @" label: bool a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,10): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 10), // (3,10): error CS1003: Syntax error, '[' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 10), // (3,40): error CS1003: Syntax error, ']' expected // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 40), // (2,1): warning CS0164: This label has not been referenced // label: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(2, 1), // (4,9): error CS0165: Use of unassigned local variable 'x1' // H.Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(4, 9), // (3,6): warning CS0168: The variable 'a' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(3, 6), // (3,9): warning CS0168: The variable 'b' is declared but never used // bool a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(3, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } } [Fact] public void GlobalCode_DeclaratorArguments_03() { string source = @" event System.Action a, b(H.TakeOutParam(1, out var x1)); H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static System.Action Dummy(params object[] x) {return null;} public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,25): error CS1528: Expected ; or = (cannot specify constructor arguments in declaration) // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_BadVarDecl, "(H.TakeOutParam(1, out var x1)").WithLocation(3, 25), // (3,25): error CS1003: Syntax error, '[' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments("[", "(").WithLocation(3, 25), // (3,55): error CS1003: Syntax error, ']' expected // event System.Action a, b(H.TakeOutParam(1, out var x1)); Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments("]", ")").WithLocation(3, 55), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_DeclaratorArguments_04() { string source = @" fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; H.Dummy(x1); void Test() { H.Dummy(x1); } class H { public static bool Dummy(params object[] x) {return true;} public static int TakeOutParam<T>(T y, out T x) { x = y; return 3; } } "; { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to 'b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelForOutField(model, x1Decl, x1Ref); } { var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (3,12): error CS0116: A namespace cannot directly contain members such as fields or methods // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(3, 12), // (3,18): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "b").WithLocation(3, 18), // (3,20): error CS0133: The expression being assigned to '<invalid-global-code>.b' must be constant // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "H.TakeOutParam(1, out var x1)").WithArguments("<invalid-global-code>.b").WithLocation(3, 20), // (3,12): error CS1642: Fixed size buffer fields may only be members of structs // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a").WithLocation(3, 12), // (3,12): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed bool a[2], b[H.TakeOutParam(1, out var x1)]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "a[2]").WithLocation(3, 12), // (4,9): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(4, 9), // (8,13): error CS0103: The name 'x1' does not exist in the current context // H.Dummy(x1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(8, 13), // (6,6): warning CS8321: The local function 'Test' is declared but never used // void Test() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Test").WithArguments("Test").WithLocation(6, 6) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); AssertContainedInDeclaratorArguments(x1Decl); VerifyModelNotSupported(model, x1Decl); VerifyNotInScope(model, x1Ref[0]); VerifyNotInScope(model, x1Ref[1]); } } [Fact] public void GlobalCode_RestrictedType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out System.ArgIterator x2); class H { public static void TakeOutParam(out System.ArgIterator x) { x = default(System.ArgIterator); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (9,37): error CS1601: Cannot make reference to variable of type 'ArgIterator' // public static void TakeOutParam(out System.ArgIterator x) Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator x").WithArguments("System.ArgIterator").WithLocation(9, 37), // (5,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out System.ArgIterator x2); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(5, 20), // (3,20): error CS0610: Field or property cannot be of type 'ArgIterator' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "var").WithArguments("System.ArgIterator").WithLocation(3, 20) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_StaticType_01() { string source = @" H.TakeOutParam(out var x1); H.TakeOutParam(out StaticType x2); class H { public static void TakeOutParam(out StaticType x) { x = default(System.ArgIterator); } } static class StaticType{} "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (5,31): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out StaticType x2); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x2").WithArguments("StaticType").WithLocation(5, 31), // (9,24): error CS0721: 'StaticType': static types cannot be used as parameters // public static void TakeOutParam(out StaticType x) Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "TakeOutParam").WithArguments("StaticType").WithLocation(9, 24), // (3,24): error CS0723: Cannot declare a variable of static type 'StaticType' // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "x1").WithArguments("StaticType").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); VerifyModelForOutField(model, x2Decl); } [Fact] public void GlobalCode_InferenceFailure_01() { string source = @" H.TakeOutParam(out var x1, x1); class H { public static void TakeOutParam(out int x, long y) { x = 1; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.GetDeclarationDiagnostics().Verify( // (3,24): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.TakeOutParam(out var x1, x1); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact] public void GlobalCode_InferenceFailure_02() { string source = @" var a = b; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_03() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = a; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var b = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single()); Assert.True(b.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = a; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); } [Fact] public void GlobalCode_InferenceFailure_04() { string source = @" var a = x1; var b = H.TakeOutParam(out var x1, a); class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var a = (IFieldSymbol)model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "a").Single()); Assert.True(a.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(3, 5) ); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = H.TakeOutParam(out var x1, a); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(4, 32) ); } [Fact] public void GlobalCode_InferenceFailure_05() { string source = @" var a = H.TakeOutParam(out var x1, b); var b = x1; class H { public static int TakeOutParam(out int x, long y) { x = 1; return 123; } } "; // `skipUsesIsNullable: true` is necessary to avoid visiting symbols eagerly in CreateCompilation, // which would result in `ERR_RecursivelyTypedVariable` reported on the other local (field). var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (3,32): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = H.TakeOutParam(out var x1, b); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(3, 32) ); compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script, skipUsesIsNullable: true); tree = compilation.SyntaxTrees.Single(); model = compilation.GetSemanticModel(tree); x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var bDecl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Where(d => d.Identifier.ValueText == "b").Single(); var b = (IFieldSymbol)model.GetDeclaredSymbol(bDecl); Assert.True(b.Type.IsErrorType()); x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()); Assert.False(x1.Type.IsErrorType()); compilation.VerifyDiagnostics( // (4,5): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition. // var b = x1; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(4, 5) ); } [Fact] public void GlobalCode_InferenceFailure_06() { string source = @" H.TakeOutParam(out var x1); class H { public static int TakeOutParam<T>(out T x) { x = default(T); return 123; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24), // (2,3): error CS0411: The type arguments for method 'H.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("H.TakeOutParam<T>(out T)").WithLocation(2, 3) ); compilation.GetDeclarationDiagnostics().Verify( // (2,24): error CS8197: Cannot infer the type of implicitly-typed out variable 'x1'. // H.TakeOutParam(out var x1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "x1").WithArguments("x1").WithLocation(2, 24) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); VerifyModelForOutField(model, x1Decl); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17377")] public void GlobalCode_InferenceFailure_07() { string source = @" H.M((var x1, int x2)); H.M(x1); class H { public static void M(object a) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10), // (2,6): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var x1").WithLocation(2, 6), // (2,14): error CS8185: A declaration is not allowed in this context. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x2").WithLocation(2, 14), // (2,5): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(var x1, int x2)").WithArguments("System.ValueTuple`2").WithLocation(2, 5), // (2,5): error CS1503: Argument 1: cannot convert from '(var, int)' to 'object' // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_BadArgType, "(var x1, int x2)").WithArguments("1", "(var, int)", "object").WithLocation(2, 5) ); compilation.GetDeclarationDiagnostics().Verify( // (2,10): error CS7019: Type of 'x1' cannot be inferred since its initializer directly or indirectly refers to the definition. // H.M((var x1, int x2)); Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "x1").WithArguments("x1").WithLocation(2, 10) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Ref.Length); VerifyModelForOutField(model, x1Decl, x1Ref); var x1 = (IFieldSymbol)model.GetDeclaredSymbol(x1Decl.VariableDesignation()); Assert.Equal("var", x1.Type.ToTestDisplayString()); Assert.True(x1.Type.IsErrorType()); } [Fact, WorkItem(17321, "https://github.com/dotnet/roslyn/issues/17321")] public void InferenceFailure_01() { string source = @" class H { object M1() => M(M(1), x1); static object M(object o1) => o1; static void M(object o1, object o2) {} } "; var node0 = SyntaxFactory.ParseCompilationUnit(source); var one = node0.DescendantNodes().OfType<LiteralExpressionSyntax>().Single(); var decl = SyntaxFactory.DeclarationExpression( type: SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("var")), designation: SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier("x1"))); var node1 = node0.ReplaceNode(one, decl); var tree = node1.SyntaxTree; Assert.NotNull(tree); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics( // (4,24): error CS8185: A declaration is not allowed in this context. // object M1() => M(M(varx1), x1); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "varx1").WithLocation(4, 24) ); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>() .Where(p => p.Identifier().ValueText == "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForDeclarationVarWithoutDataFlow(model, x1Decl, x1Ref); } [Fact] public void GlobalCode_AliasInfo_01() { string source = @" H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact] public void GlobalCode_AliasInfo_02() { string source = @" using var = System.Int32; H.TakeOutParam(1, out var x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("var=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_03() { string source = @" using a = System.Int32; H.TakeOutParam(1, out a x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Equal("a=System.Int32", model.GetAliasInfo(x1Decl.Type).ToTestDisplayString()); } [Fact] public void GlobalCode_AliasInfo_04() { string source = @" H.TakeOutParam(1, out int x1); class H { public static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe.WithScriptClassName("Script"), parseOptions: TestOptions.Script); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); Assert.Null(model.GetAliasInfo(x1Decl.Type)); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_1() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out var x1): System.Console.WriteLine(x1); break; } } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,18): error CS0150: A constant value is expected // case !TakeOutParam(3, out var x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!TakeOutParam(3, out var x1)").WithLocation(8, 18) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } [Fact, WorkItem(14717, "https://github.com/dotnet/roslyn/issues/14717")] public void ExpressionVariableInCase_2() { string source = @" class Program { static void Main(string[] args) { switch (true) { case !TakeOutParam(3, out UndeclaredType x1): System.Console.WriteLine(x1); break; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); // The point of this test is that it should not crash. compilation.VerifyDiagnostics( // (8,19): error CS0103: The name 'TakeOutParam' does not exist in the current context // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_NameNotInContext, "TakeOutParam").WithArguments("TakeOutParam").WithLocation(8, 19), // (8,39): error CS0246: The type or namespace name 'UndeclaredType' could not be found (are you missing a using directive or an assembly reference?) // case !TakeOutParam(3, out UndeclaredType x1): Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndeclaredType").WithArguments("UndeclaredType").WithLocation(8, 39) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, false, references); } private static void VerifyModelForOutFieldDuplicate( SemanticModel model, DeclarationExpressionSyntax decl, params IdentifierNameSyntax[] references) { VerifyModelForOutField(model, decl, true, references); } private static void VerifyModelForOutField( SemanticModel model, DeclarationExpressionSyntax decl, bool duplicate, params IdentifierNameSyntax[] references) { var variableDesignationSyntax = GetVariableDesignation(decl); var symbol = model.GetDeclaredSymbol(variableDesignationSyntax); Assert.Equal(decl.Identifier().ValueText, symbol.Name); Assert.Equal(SymbolKind.Field, symbol.Kind); Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax)); var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText); var names = model.LookupNames(decl.SpanStart); if (duplicate) { Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, symbols.Single()); } Assert.Contains(decl.Identifier().ValueText, names); var local = (IFieldSymbol)symbol; var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault(); var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement && (declarator.ArgumentList?.Contains(decl)).GetValueOrDefault(); // We're not able to get type information at such location (out var argument in global code) at this point // See https://github.com/dotnet/roslyn/issues/13569 AssertInfoForDeclarationExpressionSyntax(model, decl, expectedSymbol: local, expectedType: inFieldDeclaratorArgumentlist ? null : local.Type); foreach (var reference in references) { var referenceInfo = model.GetSymbolInfo(reference); symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText); if (duplicate) { Assert.Null(referenceInfo.Symbol); Assert.Contains(symbol, referenceInfo.CandidateSymbols); Assert.True(symbols.Count() > 1); Assert.Contains(symbol, symbols); } else { Assert.Same(symbol, referenceInfo.Symbol); Assert.Same(symbol, symbols.Single()); Assert.Equal(local.Type, model.GetTypeInfo(reference).Type); } Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText)); } if (!inFieldDeclaratorArgumentlist) { var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent; if (model.IsSpeculativeSemanticModel) { Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent)); } else { var dataFlow = model.AnalyzeDataFlow(dataFlowParent); if (dataFlow.Succeeded) { Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.DataFlowsOut.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.ReadOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); Assert.False(dataFlow.WrittenOutside.Contains(symbol, ReferenceEqualityComparer.Instance)); } } } } [Fact] public void MethodTypeArgumentInference_01() { var source = @" public class X { public static void Main() { TakeOutParam(out int a); TakeOutParam(out long b); } static void TakeOutParam<T>(out T x) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int64"); } [Fact] public void MethodTypeArgumentInference_02() { var source = @" public class X { public static void Main() { TakeOutParam(out var a); } static void TakeOutParam<T>(out T x) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out var a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T)").WithLocation(6, 9) ); } [Fact] public void MethodTypeArgumentInference_03() { var source = @" public class X { public static void Main() { long a = 0; TakeOutParam(out int b, a); int c; TakeOutParam(out c, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out int b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(7, 9), // (9,9): error CS0411: The type arguments for method 'X.TakeOutParam<T>(out T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // TakeOutParam(out c, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "TakeOutParam").WithArguments("X.TakeOutParam<T>(out T, T)").WithLocation(9, 9) ); } [Fact] public void MethodTypeArgumentInference_04() { var source = @" public class X { public static void Main() { byte a = 0; int b = 0; TakeOutParam(out int c, a); TakeOutParam(out b, a); } static void TakeOutParam<T>(out T x, T y) { x = default(T); System.Console.WriteLine(typeof(T)); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"System.Int32 System.Int32"); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void OutVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVar(model, x1Decl, x1Ref); Assert.Equal("System.String", model.GetTypeInfo(x1Ref).Type.ToTestDisplayString()); } [Fact] public void OutVarDiscard() { var source = @" public class C { static void Main() { M(out int _); M(out var _); M(out _); } static void M(out int x) { x = 1; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); var tree = comp.Compilation.SyntaxTrees.Single(); var model = comp.Compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetTypeInfo(discard1).Type); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetTypeInfo(discard2).Type); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("System.Int32", discard3Symbol.Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); comp.VerifyIL("C.Main()", @" { // Code size 22 (0x16) .maxstack 1 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: call ""void C.M(out int)"" IL_0007: ldloca.s V_0 IL_0009: call ""void C.M(out int)"" IL_000e: ldloca.s V_0 IL_0010: call ""void C.M(out int)"" IL_0015: ret } "); } [Fact] public void NamedOutVarDiscard() { var source = @" public class C { static void Main() { M(y: out string _, x: out int _); M(y: out var _, x: out var _); M(y: out _, x: out _); } static void M(out int x, out string y) { x = 1; y = ""hello""; System.Console.Write(""M""); } } "; var comp = CompileAndVerify(source, expectedOutput: "MMM"); comp.VerifyDiagnostics(); } [Fact] public void OutVarDiscardInCtor_01() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out int i1); new C(out int _); new C(out var _); new C(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CCCC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("int", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); var discard3 = GetDiscardIdentifiers(tree).First(); Assert.Equal("System.Int32", model.GetTypeInfo(discard3).Type.ToTestDisplayString()); var discard3Symbol = (IDiscardSymbol)model.GetSymbolInfo(discard3).Symbol; Assert.Equal("int _", discard3Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact] public void OutVarDiscardInCtor_02() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out long x1); new C(out long _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (7,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long x1); Diagnostic(ErrorCode.ERR_BadArgType, "long x1").WithArguments("1", "out long", "out int").WithLocation(7, 19), // (8,19): error CS1503: Argument 1: cannot convert from 'out long' to 'out int' // new C(out long _); Diagnostic(ErrorCode.ERR_BadArgType, "long _").WithArguments("1", "out long", "out int").WithLocation(8, 19), // (7,19): error CS0165: Use of unassigned local variable 'x1' // new C(out long x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "long x1").WithArguments("x1").WithLocation(7, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); VerifyModelForOutVarWithoutDataFlow(model, x1Decl); var discard1 = GetDiscardDesignations(tree).Single(); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("long _", declaration1.ToString()); Assert.Equal("System.Int64", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("long", declaration1.Type.ToString()); Assert.Equal("System.Int64", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int64", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int64", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); } [Fact] public void OutVarDiscardAliasInfo_01() { var source = @" using alias1 = System.Int32; using var = System.Int32; public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "CC"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Equal("alias1=System.Int32", model.GetAliasInfo(declaration1.Type).ToTestDisplayString()); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("System.Int32", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Equal("var=System.Int32", model.GetAliasInfo(declaration2.Type).ToTestDisplayString()); } [Fact] public void OutVarDiscardAliasInfo_02() { var source = @" enum alias1 : long {} class var {} public class C { public C(out int i) { i = 1; System.Console.Write(""C""); } static void Main() { new C(out alias1 _); new C(out var _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,19): error CS1503: Argument 1: cannot convert from 'out alias1' to 'out int' // new C(out alias1 _); Diagnostic(ErrorCode.ERR_BadArgType, "alias1 _").WithArguments("1", "out alias1", "out int").WithLocation(10, 19), // (11,19): error CS1503: Argument 1: cannot convert from 'out var' to 'out int' // new C(out var _); Diagnostic(ErrorCode.ERR_BadArgType, "var _").WithArguments("1", "out var", "out int").WithLocation(11, 19) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).ElementAt(0); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetSymbolInfo(discard1).Symbol); var declaration1 = (DeclarationExpressionSyntax)discard1.Parent; Assert.Equal("alias1 _", declaration1.ToString()); Assert.Equal("alias1", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Null(model.GetSymbolInfo(declaration1).Symbol); Assert.Equal("alias1", declaration1.Type.ToString()); Assert.Equal("alias1", model.GetSymbolInfo(declaration1.Type).Symbol.ToTestDisplayString()); TypeInfo typeInfo = model.GetTypeInfo(declaration1.Type); Assert.Equal("alias1", typeInfo.Type.ToTestDisplayString()); Assert.Equal("alias1", typeInfo.ConvertedType.ToTestDisplayString()); Assert.True(model.GetConversion(declaration1.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration1.Type)); var discard2 = GetDiscardDesignations(tree).ElementAt(1); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (DeclarationExpressionSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Equal("var", model.GetTypeInfo(declaration2).Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, model.GetTypeInfo(declaration2).Type.TypeKind); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); Assert.Equal("var", declaration2.Type.ToString()); Assert.Equal("var", model.GetSymbolInfo(declaration2.Type).Symbol.ToTestDisplayString()); typeInfo = model.GetTypeInfo(declaration2.Type); Assert.Equal("var", typeInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal(typeInfo.Type, typeInfo.ConvertedType); Assert.True(model.GetConversion(declaration2.Type).IsIdentity); Assert.Null(model.GetAliasInfo(declaration2.Type)); } [Fact] public void OutVarDiscardInCtorInitializer() { var source = @" public class C { public C(out int i) { i = 1; System.Console.Write(""C ""); } static void Main() { new Derived2(out int i2); new Derived3(out int i3); new Derived4(); } } public class Derived2 : C { public Derived2(out int i) : base(out int _) { i = 2; System.Console.Write(""Derived2 ""); } } public class Derived3 : C { public Derived3(out int i) : base(out var _) { i = 3; System.Console.Write(""Derived3 ""); } } public class Derived4 : C { public Derived4(out int i) : base(out _) { i = 4; } public Derived4() : this(out _) { System.Console.Write(""Derived4""); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "C Derived2 C Derived3 C Derived4"); } [Fact] public void DiscardNotRecognizedInOtherScenarios() { var source = @" public class C { void M<T>() { _.ToString(); M(_); _<T>.ToString(); (_<T>, _<T>) = (1, 2); M<_>(); new C() { _ = 1 }; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (6,9): error CS0103: The name '_' does not exist in the current context // _.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 9), // (7,11): error CS0103: The name '_' does not exist in the current context // M(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(7, 11), // (8,9): error CS0103: The name '_' does not exist in the current context // _<T>.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(8, 9), // (9,10): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 10), // (9,16): error CS0103: The name '_' does not exist in the current context // (_<T>, _<T>) = (1, 2); Diagnostic(ErrorCode.ERR_NameNotInContext, "_<T>").WithArguments("_").WithLocation(9, 16), // (10,11): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // M<_>(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(10, 11), // (11,19): error CS0117: 'C' does not contain a definition for '_' // new C() { _ = 1 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "_").WithArguments("C", "_").WithLocation(11, 19) ); } [Fact] public void TypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); System.Console.Write(t.GetType().ToString()); } static void Main() { M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "System.Int32"); } [Fact] public void UntypedDiscardInMethodTypeInference() { var source = @" public class C { static void M<T>(out T t) { t = default(T); } static void Main() { M(out var _); M(out _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out var _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(10, 9), // (11,9): error CS0411: The type arguments for method 'C.M<T>(out T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M(out _); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(out T)").WithLocation(11, 9) ); } [Fact] public void PickOverloadWithTypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; System.Console.Write(""object returning M. ""); } static void M(out int x) { x = 2; System.Console.Write(""int returning M.""); } static void Main() { M(out object _); M(out int _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "object returning M. int returning M."); } [Fact] public void CannotPickOverloadWithUntypedDiscard() { var source = @" public class C { static void M(out object x) { x = 1; } static void M(out int x) { x = 2; } static void Main() { M(out var _); M(out _); M(out byte _); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out var _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(8, 9), // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(out object)' and 'C.M(out int)' // M(out _); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(out object)", "C.M(out int)").WithLocation(9, 9), // (10,15): error CS1503: Argument 1: cannot convert from 'out byte' to 'out object' // M(out byte _); Diagnostic(ErrorCode.ERR_BadArgType, "byte _").WithArguments("1", "out byte", "out object").WithLocation(10, 15) ); } [Fact] public void NoOverloadWithDiscard() { var source = @" public class A { } public class B : A { static void M(A a) { a.M2(out A x); a.M2(out A _); } } public static class S { public static void M2(this A self, out B x) { x = null; } }"; var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll, references: new[] { Net40.SystemCore }); comp.VerifyDiagnostics( // (7,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A x); Diagnostic(ErrorCode.ERR_BadArgType, "A x").WithArguments("2", "out A", "out B").WithLocation(7, 18), // (8,18): error CS1503: Argument 2: cannot convert from 'out A' to 'out B' // a.M2(out A _); Diagnostic(ErrorCode.ERR_BadArgType, "A _").WithArguments("2", "out A", "out B").WithLocation(8, 18) ); } [Fact] [WorkItem(363727, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/363727")] public void FindCorrectBinderOnEmbeddedStatementWithMissingIdentifier() { var source = @" public class C { static void M(string x) { if(true) && int.TryParse(x, out int y)) id(iVal); // Note that the embedded statement is parsed as a missing identifier, followed by && with many spaces attached as leading trivia } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(n => n.ToString() == "x").Single(); Assert.Equal("x", x.ToString()); Assert.Equal("System.String x", model.GetSymbolInfo(x).Symbol.ToTestDisplayString()); } [Fact] public void DuplicateDeclarationInSwitchBlock() { var text = @" public class C { public static void Main(string[] args) { switch (args.Length) { case 0: M(M(out var x1), x1); M(M(out int x1), x1); break; case 1: M(M(out int x1), x1); break; } } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics( // (10,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(10, 29), // (13,29): error CS0128: A local variable or function named 'x1' is already defined in this scope // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(13, 29), // (13,34): error CS0165: Use of unassigned local variable 'x1' // M(M(out int x1), x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 34) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var x6Decl = GetOutVarDeclarations(tree, "x1").ToArray(); var x6Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(3, x6Decl.Length); Assert.Equal(3, x6Ref.Length); VerifyModelForOutVar(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[2]); } [Fact] public void DeclarationInLocalFunctionParameterDefault() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(int a, int b) => a+b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,75): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 75), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out int z1), z1)").WithArguments("b").WithLocation(6, 30), // (6,61): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 61), // (7,75): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 75), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(M(out var z2), z2)").WithArguments("b").WithLocation(7, 30), // (7,61): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 61), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInAnonymousMethodParameterDefault() { var text = @" class C { public static void Main(int arg) { System.Action<bool, int> d1 = delegate ( bool b = M(M(out int z1), z1), int s2 = z1) { var t = z1; }; System.Action<bool, int> d2 = delegate ( bool b = M(M(out var z2), z2), int s2 = z2) { var t = z2; }; int x = z1 + z2; d1 = d2 = null; } static int M(out int z) => z = 1; static int M(int a, int b) => a+b; } "; // the scope of an expression variable introduced in the default expression // of a lambda parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_DefaultValueNotAllowed).Verify( // (9,55): error CS0103: The name 'z1' does not exist in the current context // { var t = z1; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 55), // (13,55): error CS0103: The name 'z2' does not exist in the current context // { var t = z2; }; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(13, 55), // (15,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(15, 17), // (15,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(15, 22) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var z1 = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "z1").First(); Assert.Equal("System.Int32", model.GetTypeInfo(z1).Type.ToTestDisplayString()); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void Scope_LocalFunction_Attribute_01() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out int x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out int x4))] [Test(p = TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(p1 = TakeOutParam(out int x6) && x6 > 0, p2 = TakeOutParam(out int x6) && x6 > 0)] [Test(p = TakeOutParam(out int x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_02() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out int x3) && x3 > 0)] [Test(x4 && TakeOutParam(out int x4))] [Test(TakeOutParam(51, out int x5) && TakeOutParam(52, out int x5) && x5 > 0)] [Test(TakeOutParam(out int x6) && x6 > 0, TakeOutParam(out int x6) && x6 > 0)] [Test(TakeOutParam(out int x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out int x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out int x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out int x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_03() { var source = @" public class X { public static void Main() { void Local1( [Test(p = TakeOutParam(out var x3) && x3 > 0)] [Test(p = x4 && TakeOutParam(out var x4))] [Test(p = TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(p1 = TakeOutParam(out var x6) && x6 > 0, p2 = TakeOutParam(out var x6) && x6 > 0)] [Test(p = TakeOutParam(out var x7) && x7 > 0)] [Test(p = x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} public bool p1 {get; set;} public bool p2 {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,23): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(p = x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 23), // (10,48): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 48), // (13,45): error CS0128: A local variable or function named 'x6' is already defined in this scope // p2 = TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 45), // (15,23): error CS0103: The name 'x7' does not exist in the current context // [Test(p = x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 23) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_04() { var source = @" public class X { public static void Main() { void Local1( [Test(TakeOutParam(out var x3) && x3 > 0)] [Test(x4 && TakeOutParam(out var x4))] [Test(TakeOutParam(51, out var x5) && TakeOutParam(52, out var x5) && x5 > 0)] [Test(TakeOutParam(out var x6) && x6 > 0, TakeOutParam(out var x6) && x6 > 0)] [Test(TakeOutParam(out var x7) && x7 > 0)] [Test(x7 > 2)] int p1) { Dummy(x7, p1); } Local1(1); } bool Dummy(params object[] x) {return true;} static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} public Test(bool p1, bool p2) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (18,19): error CS0103: The name 'x7' does not exist in the current context // Dummy(x7, p1); Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(18, 19), // (8,19): error CS0841: Cannot use local variable 'x4' before it is declared // [Test(x4 && TakeOutParam(out var x4))] Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x4").WithArguments("x4").WithLocation(8, 19), // (10,44): error CS0128: A local variable or function named 'x5' is already defined in this scope // TakeOutParam(52, out var x5) && Diagnostic(ErrorCode.ERR_LocalDuplicate, "x5").WithArguments("x5").WithLocation(10, 44), // (13,40): error CS0128: A local variable or function named 'x6' is already defined in this scope // TakeOutParam(out var x6) && x6 > 0)] Diagnostic(ErrorCode.ERR_LocalDuplicate, "x6").WithArguments("x6").WithLocation(13, 40), // (15,19): error CS0103: The name 'x7' does not exist in the current context // [Test(x7 > 2)] Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(15, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetOutVarDeclaration(tree, "x3"); var x3Ref = GetReference(tree, "x3"); VerifyModelForOutVarInNotExecutableCode(model, x3Decl, x3Ref); var x4Decl = GetOutVarDeclaration(tree, "x4"); var x4Ref = GetReference(tree, "x4"); VerifyModelForOutVarInNotExecutableCode(model, x4Decl, x4Ref); var x5Decl = GetOutVarDeclarations(tree, "x5").ToArray(); var x5Ref = GetReference(tree, "x5"); Assert.Equal(2, x5Decl.Length); VerifyModelForOutVarInNotExecutableCode(model, x5Decl[0], x5Ref); VerifyModelForOutVarDuplicateInSameScope(model, x5Decl[1]); var x6Decl = GetOutVarDeclarations(tree, "x6").ToArray(); var x6Ref = GetReferences(tree, "x6").ToArray(); Assert.Equal(2, x6Decl.Length); Assert.Equal(2, x6Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x6Decl[0], x6Ref); VerifyModelForOutVarDuplicateInSameScope(model, x6Decl[1]); var x7Decl = GetOutVarDeclaration(tree, "x7"); var x7Ref = GetReferences(tree, "x7").ToArray(); Assert.Equal(3, x7Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x7Decl, x7Ref[0]); VerifyNotInScope(model, x7Ref[1]); VerifyNotInScope(model, x7Ref[2]); } [Fact] public void Scope_LocalFunction_Attribute_05() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public bool p {get; set;} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,44): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(p = TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 44) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_LocalFunction_Attribute_06() { var source = @" public class X { public static void Main() { TakeOutParam(out var x1); TakeOutParam(out var x2); void Local1( [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] int p1) { p1 = 0; } Local1(x2); } static bool TakeOutParam(out int x) { x = 123; return true; } } class Test : System.Attribute { public Test(bool p) {} } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); compilation.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_BadAttributeArgument).Verify( // (10,40): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // [Test(TakeOutParam(out int x2) && x1 > 0 && x2 > 0)] Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(10, 40) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclaration(tree, "x1"); var x1Ref = GetReference(tree, "x1"); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").ToArray(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVar(model, x2Decl[0], x2Ref[1]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl[1], x2Ref[0]); } [Fact] public void Scope_InvalidArrayDimensions01() { var text = @" public class Cls { public static void Main() { int x1 = 0; int[Test1(out int x1), x1] _1; int[Test1(out int x2), x2] x2; } static int Test1(out int x) { x = 1; return 1; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (7,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x1), x1]").WithLocation(7, 12), // (7,27): error CS0128: A local variable or function named 'x1' is already defined in this scope // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 27), // (8,12): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[Test1(out int x2), x2]").WithLocation(8, 12), // (8,36): error CS0128: A local variable or function named 'x2' is already defined in this scope // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(8, 36), // (6,13): warning CS0219: The variable 'x1' is assigned but its value is never used // int x1 = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x1").WithArguments("x1").WithLocation(6, 13), // (7,27): warning CS0168: The variable 'x1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x1").WithArguments("x1").WithLocation(7, 27), // (7,36): warning CS0168: The variable '_1' is declared but never used // int[Test1(out int x1), x1] _1; Diagnostic(ErrorCode.WRN_UnreferencedVar, "_1").WithArguments("_1").WithLocation(7, 36), // (8,27): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 27), // (8,36): warning CS0168: The variable 'x2' is declared but never used // int[Test1(out int x2), x2] x2; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(8, 36) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); VerifyNotAnOutLocal(model, x1Ref); VerifyModelForOutVarDuplicateInSameScope(model, x1Decl); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref); } [Fact] public void Scope_InvalidArrayDimensions_02() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using (int[] d = null) { Dummy(x1); } } void Test2() { using (int[] d = null) Dummy(x2); } void Test3() { var x3 = 11; Dummy(x3); using (int[] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 3; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // file.cs(12,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x1),x1] d = null").WithArguments("int[*,*]").WithLocation(12, 16), // file.cs(12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 19), // file.cs(12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // file.cs(12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x1),x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // file.cs(14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // file.cs(20,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x2),x2] d = null").WithArguments("int[*,*]").WithLocation(20, 16), // file.cs(20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(20, 19), // file.cs(20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // file.cs(20,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x2),x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 51), // file.cs(21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // file.cs(29,16): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "int[TakeOutParam(true, out var x3),x3] d = null").WithArguments("int[*,*]").WithLocation(29, 16), // file.cs(29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3),x3]").WithLocation(29, 19), // file.cs(29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // file.cs(29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // file.cs(29,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using (int[TakeOutParam(true, out var x3),x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 51), // file.cs(30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_03() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} void Test1() { using int[TakeOutParam(true, out var x1), x1] d = null; Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); using int[TakeOutParam(true, out var x2), x2] d = null; Dummy(x2); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (12,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x1), x1] d = null;").WithArguments("int[*,*]").WithLocation(12, 9), // (12,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 18), // (12,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 19), // (12,51): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x1), x1] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 51), // (13,15): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 15), // (21,9): error CS1674: 'int[*,*]': type used in a using statement must be implicitly convertible to 'System.IDisposable'. // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using int[TakeOutParam(true, out var x2), x2] d = null;").WithArguments("int[*,*]").WithLocation(21, 9), // (21,18): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(21, 18), // (21,19): error CS0029: Cannot implicitly convert type 'bool' to 'int' // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 19), // (21,46): error CS0128: A local variable or function named 'x2' is already defined in this scope // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x2").WithArguments("x2").WithLocation(21, 46), // (21,46): warning CS0168: The variable 'x2' is declared but never used // using int[TakeOutParam(true, out var x2), x2] d = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "x2").WithArguments("x2").WithLocation(21, 46) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyNotAnOutLocal(model, x2Ref[1]); VerifyNotAnOutLocal(model, x2Ref[2]); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, isShadowed: true); } [Fact] public void Scope_InvalidArrayDimensions_04() { var source = @" public class X { public static void Main() { } bool Dummy(object x) {return true;} void Test1() { for (int[] a = null;;) Dummy(x1); } void Test2() { var x2 = 11; Dummy(x2); for (int[] a = null;;) Dummy(x2); } static bool TakeOutParam(object y, out bool x) { x = true; return true; } } "; // replace 'int[]' with 'int[TakeOutParam(true, out var x1), x1]' var syntaxTree = Parse(source, filename: "file.cs"); for (int i = 0; i < 2; i++) { var method = syntaxTree.GetCompilationUnitRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ElementAt(i + 2); var rankSpecifierOld = method.DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); { var rankSpecifierNew = rankSpecifierOld .WithSizes(SyntaxFactory.SeparatedList<ExpressionSyntax>( SyntaxFactory.NodeOrTokenList( SyntaxFactory.ParseExpression($"TakeOutParam(true, out var x{i + 1})"), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.ParseExpression($"x{i + 1}") ))); syntaxTree = syntaxTree.GetCompilationUnitRoot().ReplaceNode(rankSpecifierOld, rankSpecifierNew).SyntaxTree; } } var compilation = CreateCompilation(syntaxTree, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // file.cs(12,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1),x1]").WithLocation(12, 17), // file.cs(12,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 18), // file.cs(12,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 49), // file.cs(13,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(13, 19), // file.cs(12,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x1),x1] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(12, 53), // file.cs(21,17): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2),x2]").WithLocation(21, 17), // file.cs(21,45): error CS0136: A local or parameter named 'x2' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x2").WithArguments("x2").WithLocation(21, 45), // file.cs(21,18): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(21, 18), // file.cs(21,49): error CS0029: Cannot implicitly convert type 'bool' to 'int' // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(21, 49), // file.cs(22,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(22, 19), // file.cs(21,53): warning CS0219: The variable 'a' is assigned but its value is never used // for (int[TakeOutParam(true, out var x2),x2] a = null;;) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(21, 53) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarInNotExecutableCode(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(3, x2Ref.Length); VerifyNotAnOutLocal(model, x2Ref[0]); VerifyModelForOutVarInNotExecutableCode(model, x2Decl, x2Ref[1], x2Ref[2]); } [Fact] public void Scope_InvalidArrayDimensions_05() { var source = @" public class X { public static void Main() { } System.IDisposable Dummy(object x) {return null;} unsafe void Test1() { fixed (int[TakeOutParam(true, out var x1), x1] d = null) { Dummy(x1); } } unsafe void Test2() { fixed (int[TakeOutParam(true, out var x2), x2] d = null) Dummy(x2); } unsafe void Test3() { var x3 = 11; Dummy(x3); fixed (int[TakeOutParam(true, out var x3), x3] d = null) Dummy(x3); } static bool TakeOutParam<T>(T y, out T x) { x = y; return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (10,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test1() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test1").WithLocation(10, 17), // (12,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x1), x1]").WithLocation(12, 19), // (12,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x1)").WithArguments("bool", "int").WithLocation(12, 20), // (12,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("bool", "int").WithLocation(12, 52), // (12,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x1), x1] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(12, 56), // (14,19): error CS0165: Use of unassigned local variable 'x1' // Dummy(x1); Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(14, 19), // (18,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test2() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test2").WithLocation(18, 17), // (20,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x2), x2]").WithLocation(20, 19), // (20,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x2)").WithArguments("bool", "int").WithLocation(20, 20), // (20,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("bool", "int").WithLocation(20, 52), // (20,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x2), x2] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(20, 56), // (21,19): error CS0165: Use of unassigned local variable 'x2' // Dummy(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(21, 19), // (24,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Test3() Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Test3").WithLocation(24, 17), // (29,19): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[TakeOutParam(true, out var x3), x3]").WithLocation(29, 19), // (29,20): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "TakeOutParam(true, out var x3)").WithArguments("bool", "int").WithLocation(29, 20), // (29,47): error CS0136: A local or parameter named 'x3' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x3").WithArguments("x3").WithLocation(29, 47), // (29,52): error CS0029: Cannot implicitly convert type 'bool' to 'int' // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_NoImplicitConv, "x3").WithArguments("bool", "int").WithLocation(29, 52), // (29,56): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed (int[TakeOutParam(true, out var x3), x3] d = null) Diagnostic(ErrorCode.ERR_BadFixedInitType, "d = null").WithLocation(29, 56), // (30,19): error CS0165: Use of unassigned local variable 'x3' // Dummy(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(30, 19) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetOutVarDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x1Decl, x1Ref); var x2Decl = GetOutVarDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForOutVarWithoutDataFlow(model, x2Decl, x2Ref); var x3Decl = GetOutVarDeclarations(tree, "x3").Single(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(3, x3Ref.Length); VerifyNotAnOutLocal(model, x3Ref[0]); VerifyModelForOutVarWithoutDataFlow(model, x3Decl, x3Ref[1], x3Ref[2]); } [Fact] public void DeclarationInNameof_00() { var text = @" class C { public static void Main() { var x = nameof(M2(M1(out var x1), x1)).ToString(); } static int M1(out int z) => z = 1; static int M2(int a, int b) => 2; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,24): error CS8081: Expression does not have a name. // var x = nameof(M2(M1(out var x1), x1)).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M2(M1(out var x1), x1)").WithLocation(6, 24) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "x1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(1, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] public void DeclarationInNameof_01() { var text = @" class C { public static void Main(int arg) { void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } int x = z1 + z2; } static int M(out int z) => z = 1; static bool M(object a, int b) => b == 0; } "; // the scope of an expression variable introduced in the default expression // of a local function parameter is that default expression. var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,83): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 83), // (6,39): error CS8081: Expression does not have a name. // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 39), // (6,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out int z1)), z1)").WithArguments("b").WithLocation(6, 30), // (6,69): error CS0103: The name 'z1' does not exist in the current context // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 69), // (7,83): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 83), // (7,39): error CS8081: Expression does not have a name. // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 39), // (7,30): error CS1736: Default parameter value for 'b' must be a compile-time constant // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 30), // (7,69): error CS0103: The name 'z2' does not exist in the current context // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(7, 69), // (9,17): error CS0103: The name 'z1' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(9, 17), // (9,22): error CS0103: The name 'z2' does not exist in the current context // int x = z1 + z2; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(9, 22), // (6,14): warning CS8321: The local function 'Local2' is declared but never used // void Local2(bool b = M(nameof(M(out int z1)), z1), int s2 = z1) { var t = z1; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local2").WithArguments("Local2").WithLocation(6, 14), // (7,14): warning CS8321: The local function 'Local5' is declared but never used // void Local5(bool b = M(nameof(M(out var z2)), z2), int s2 = z2) { var t = z2; } Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Local5").WithArguments("Local5").WithLocation(7, 14) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(4, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, reference: refs[0]); VerifyNotInScope(model, refs[1]); VerifyNotInScope(model, refs[2]); VerifyNotInScope(model, refs[3]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02a() { var text = @" [My(C.M(nameof(C.M(out int z1)), z1), z1)] [My(C.M(nameof(C.M(out var z2)), z2), z2)] class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (2,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 16), // (2,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 5), // (2,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 39), // (3,16): error CS8081: Expression does not have a name. // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 16), // (3,5): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 5), // (3,39): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 39) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_02b() { var text1 = @" [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] "; var text2 = @" class C { public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } class MyAttribute: System.Attribute { public MyAttribute(bool x, int y) {} } "; var compilation = CreateCompilationWithMscorlib45(new[] { text1, text2 }); compilation.VerifyDiagnostics( // (2,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out int z1)").WithLocation(2, 26), // (2,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out int z1)), z1)").WithLocation(2, 15), // (2,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out int z1)), z1), z1)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z1").WithLocation(2, 49), // (3,26): error CS8081: Expression does not have a name. // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M(out var z2)").WithLocation(3, 26), // (3,15): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "C.M(nameof(C.M(out var z2)), z2)").WithLocation(3, 15), // (3,49): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [assembly: My(C.M(nameof(C.M(out var z2)), z2), z2)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "z2").WithLocation(3, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_03() { var text = @" class C { public static void Main(string[] args) { switch ((object)args.Length) { case !M(nameof(M(out int z1)), z1): System.Console.WriteLine(z1); break; case !M(nameof(M(out var z2)), z2): System.Console.WriteLine(z2); break; } } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (8,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(8, 28), // (8,18): error CS0150: A constant value is expected // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out int z1)), z1)").WithLocation(8, 18), // (11,28): error CS8081: Expression does not have a name. // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(11, 28), // (11,18): error CS0150: A constant value is expected // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_ConstantExpected, "!M(nameof(M(out var z2)), z2)").WithLocation(11, 18), // (8,44): error CS0165: Use of unassigned local variable 'z1' // case !M(nameof(M(out int z1)), z1): Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(8, 44), // (11,44): error CS0165: Use of unassigned local variable 'z2' // case !M(nameof(M(out var z2)), z2): Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(11, 44) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_04() { var text = @" class C { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); const bool c = (z1 + z2) == 0; public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (5,29): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(5, 29), // (5,20): error CS0133: The expression being assigned to 'C.b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("C.b").WithLocation(5, 20), // (6,21): error CS0103: The name 'z1' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(6, 21), // (6,26): error CS0103: The name 'z2' does not exist in the current context // const bool c = (z1 + z2) == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z2").WithArguments("z2").WithLocation(6, 26), // (4,29): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(4, 29), // (4,20): error CS0133: The expression being assigned to 'C.a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("C.a").WithLocation(4, 20) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_05() { var text = @" class C { public static void Main(string[] args) { const bool a = M(nameof(M(out int z1)), z1); const bool b = M(nameof(M(out var z2)), z2); bool c = (z1 + z2) == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,33): error CS8081: Expression does not have a name. // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out int z1)").WithLocation(6, 33), // (6,24): error CS0133: The expression being assigned to 'a' must be constant // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out int z1)), z1)").WithArguments("a").WithLocation(6, 24), // (7,33): error CS8081: Expression does not have a name. // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "M(out var z2)").WithLocation(7, 33), // (7,24): error CS0133: The expression being assigned to 'b' must be constant // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_NotConstantExpression, "M(nameof(M(out var z2)), z2)").WithArguments("b").WithLocation(7, 24), // (6,49): error CS0165: Use of unassigned local variable 'z1' // const bool a = M(nameof(M(out int z1)), z1); Diagnostic(ErrorCode.ERR_UseDefViolation, "z1").WithArguments("z1").WithLocation(6, 49), // (7,49): error CS0165: Use of unassigned local variable 'z2' // const bool b = M(nameof(M(out var z2)), z2); Diagnostic(ErrorCode.ERR_UseDefViolation, "z2").WithArguments("z2").WithLocation(7, 49) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); for (int i = 1; i <= 2; i++) { var name = $"z{i}"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVarInNotExecutableCode(model, decl, refs); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } } [Fact] public void DeclarationInNameof_06() { var text = @" class C { public static void Main(string[] args) { string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); bool c = z1 == 0; } public static int M(out int z) => z = 1; public static bool M(object a, int b) => b == 0; } "; var compilation = CreateCompilationWithMscorlib45(text); compilation.VerifyDiagnostics( // (6,27): error CS8081: Expression does not have a name. // string s = nameof((System.Action)(() => M(M(out var z1), z1))).ToString(); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(System.Action)(() => M(M(out var z1), z1))").WithLocation(6, 27), // (7,18): error CS0103: The name 'z1' does not exist in the current context // bool c = z1 == 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "z1").WithArguments("z1").WithLocation(7, 18) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var name = "z1"; var decl = GetOutVarDeclaration(tree, name); var refs = GetReferences(tree, name).ToArray(); Assert.Equal(2, refs.Length); VerifyModelForOutVar(model, decl, isDelegateCreation: false, isExecutableCode: false, isShadowed: false, references: refs[0]); VerifyNotInScope(model, refs[1]); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("System.Int32", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_01() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p => { weakRef.TryGetTarget(out var x); }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_02() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { weakRef.TryGetTarget(out var x); }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_03() { string source = @" class C { void M<T>() { void Local1 (Action<T> onNext = p1 => { void Local1 (Action<T> onNext = p2 => { void Local1 (Action<T> onNext = p3 => { weakRef.TryGetTarget(out var x); }) { } }) { } }) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_04() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_05() { string source = @" class C { void M<T>() { void Local1 (object onNext = from p in y select (Action<T>)( p => { void Local2 (object onNext = from p in y select weakRef.TryGetTarget(out var x)) { } } ) ) { } } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); // crashes var decl = GetOutVarDeclaration(tree, "x"); VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_06() { string source = @" class C { void M<T>() { System.Type t = typeof(int[p => { weakRef.TryGetTarget(out var x); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_07() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { weakRef.TryGetTarget(out var x); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_08() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[p1 => { System.Type t2 = typeof(int[p2 => { System.Type t3 = typeof(int[p3 => { weakRef.TryGetTarget(out var x); }]); }]); }]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_09() { string source = @" class C { void M<T>() { System.Type t = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(16919, "https://github.com/dotnet/roslyn/issues/16919")] [WorkItem(378641, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=378641")] public void GetEnclosingBinderInternalRecovery_10() { string source = @" class C { void M<T>() { System.Type t1 = typeof(int[from p in y select (Action<T>)( p => { System.Type t2 = typeof(int[from p in y select weakRef.TryGetTarget(out var x)]); } ) ] ); } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varType = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "var").Single(); Assert.Equal("var", varType.ToString()); Assert.Null(model.GetAliasInfo(varType)); var decl = GetOutVarDeclaration(tree, "x"); Assert.Equal("var", model.GetTypeInfo(decl).Type.ToTestDisplayString()); // crashes VerifyModelForOutVarInNotExecutableCode(model, decl); var symbol = (ILocalSymbol)model.GetDeclaredSymbol(decl.Designation); Assert.Equal("var", symbol.Type.ToTestDisplayString()); } [Fact] [WorkItem(445600, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=445600")] public void GetEnclosingBinderInternalRecovery_11() { var text = @" class Program { static void Main(string[] args) { foreach other(some().F(a => TestOutVar(out var x) ? x : 1)); } static void TestOutVar(out int a) { a = 0; } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,16): error CS1003: Syntax error, '(' expected // foreach Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("(", "").WithLocation(6, 16), // (7,60): error CS1515: 'in' expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InExpected, ";").WithLocation(7, 60), // (7,60): error CS0230: Type and identifier are both required in a foreach statement // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_BadForeachDecl, ";").WithLocation(7, 60), // (7,60): error CS1525: Invalid expression term ';' // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(7, 60), // (7,60): error CS1026: ) expected // other(some().F(a => TestOutVar(out var x) ? x : 1)); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(7, 60) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xDecl = GetOutVarDeclaration(tree, "x"); var xRef = GetReferences(tree, "x", 1); VerifyModelForOutVarWithoutDataFlow(model, xDecl, xRef); Assert.Equal("System.Int32", compilation.GetSemanticModel(tree).GetTypeInfo(xRef[0]).Type.ToTestDisplayString()); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates() { var source = @"using System; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Func<int, bool> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (6,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(6, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Expression() { var source = @"using System; using System.Linq.Expressions; class C { static void Main() { G(x => x > 0 && F(out var y) && y > 0); } static bool F(out int i) { i = 0; return true; } static void G(Expression<Func<int, bool>> f, object o) { } static void G(C c, object o) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'G' takes 1 arguments // G(x => x > 0 && F(out var y) && y > 0); Diagnostic(ErrorCode.ERR_BadArgCount, "G").WithArguments("G", "1").WithLocation(7, 9)); } [Fact] [WorkItem(17208, "https://github.com/dotnet/roslyn/issues/17208")] public void ErrorRecoveryShouldIgnoreNonDelegates_Query() { var source = @"using System.Linq; class C { static void M() { var c = from x in new[] { 1, 2, 3 } group x > 1 && F(out var y) && y == null by x; } static bool F(out object o) { o = null; return true; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public void SpeculativeSemanticModelWithOutDiscard() { var source = @"class C { static void F() { C.G(out _); } static void G(out object o) { o = null; } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var identifierBefore = GetReferences(tree, "G").Single(); Assert.Equal(tree, identifierBefore.Location.SourceTree); var statementBefore = identifierBefore.Ancestors().OfType<StatementSyntax>().First(); var statementAfter = SyntaxFactory.ParseStatement(@"G(out _);"); bool success = model.TryGetSpeculativeSemanticModel(statementBefore.SpanStart, statementAfter, out model); Assert.True(success); var identifierAfter = statementAfter.DescendantNodes().OfType<IdentifierNameSyntax>().Single(id => id.Identifier.ValueText == "G"); Assert.Null(identifierAfter.Location.SourceTree); var info = model.GetSymbolInfo(identifierAfter); Assert.Equal("void C.G(out System.Object o)", info.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(10604, "https://github.com/dotnet/roslyn/issues/10604")] [WorkItem(16306, "https://github.com/dotnet/roslyn/issues/16306")] public void GetForEachSymbolInfoWithOutVar() { var source = @"using System.Collections.Generic; public class C { void M() { foreach (var x in M2(out int i)) { } } IEnumerable<object> M2(out int j) { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var foreachStatement = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var info = model.GetForEachStatementInfo(foreachStatement); Assert.Equal("System.Object", info.ElementType.ToTestDisplayString()); Assert.Equal("System.Collections.Generic.IEnumerator<System.Object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator()", info.GetEnumeratorMethod.ToTestDisplayString()); } [WorkItem(19382, "https://github.com/dotnet/roslyn/issues/19382")] [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] public void DiscardAndArgList() { var text = @" using System; public class C { static void Main() { M(out _, __arglist(2, 3, true)); } static void M(out int x, __arglist) { x = 0; DumpArgs(new ArgIterator(__arglist)); } static void DumpArgs(ArgIterator args) { while(args.GetRemainingCount() > 0) { TypedReference tr = args.GetNextArg(); object arg = TypedReference.ToObject(tr); Console.Write(arg); } } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "23True"); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_01() { var text = @" public class C { static void Main() { M(1, __arglist(out int y)); M(2, __arglist(out var z)); System.Console.WriteLine(z); } static void M(int x, __arglist) { x = 0; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(1, __arglist(out int y)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 28), // (7,32): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 32), // (7,28): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // M(2, __arglist(out var z)); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 28) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [Fact] [WorkItem(23378, "https://github.com/dotnet/roslyn/issues/23378")] public void OutVarInArgList_02() { var text = @" public class C { static void Main() { __arglist(out int y); __arglist(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out int y); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "int y").WithLocation(6, 23), // (6,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out int y); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out int y)").WithLocation(6, 9), // (7,27): error CS8197: Cannot infer the type of implicitly-typed out variable 'z'. // __arglist(out var z); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "z").WithArguments("z").WithLocation(7, 27), // (7,23): error CS8378: __arglist cannot have an argument passed by 'in' or 'out' // __arglist(out var z); Diagnostic(ErrorCode.ERR_CantUseInOrOutInArglist, "var z").WithLocation(7, 23), // (7,9): error CS0226: An __arglist expression may only appear inside of a call or new expression // __arglist(out var z); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist(out var z)").WithLocation(7, 9) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVar(model, zDecl, zRef); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_01() { var text = @" public class C { static void M<T>() where T : new() { var x = new T(out var z); System.Console.WriteLine(z); } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z); Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z)").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z)", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out var z)') Children(1): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void OutVarInNewT_02() { var text = @" public class C { static void M<T>() where T : C, new() { var x = new T(out var z) {F1 = 1}; System.Console.WriteLine(z); } public int F1; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics( // (6,17): error CS0417: 'T': cannot provide arguments when creating an instance of a variable type // var x = new T(out var z) {F1 = 1}; Diagnostic(ErrorCode.ERR_NewTyvarWithArgs, "new T(out var z) {F1 = 1}").WithArguments("T").WithLocation(6, 17) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var zDecl = GetOutVarDeclaration(tree, "z"); var zRef = GetReference(tree, "z"); VerifyModelForOutVarWithoutDataFlow(model, zDecl, zRef); var node = tree.GetRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single(); Assert.Equal("new T(out var z) {F1 = 1}", node.ToString()); compilation.VerifyOperationTree(node, expectedOperationTree: @" IInvalidOperation (OperationKind.Invalid, Type: T, IsInvalid) (Syntax: 'new T(out v ... z) {F1 = 1}') Children(2): IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'z') IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: '{F1 = 1}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'F1 = 1') Left: IFieldReferenceOperation: System.Int32 C.F1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'F1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'F1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } static bool TakeOutParam(int y, out int x) { x = y; return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,76): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(TakeOutParam(1, out int x1) && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "int x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 76) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void ConstructorBodyOperation() { var text = @" public class C { C() : this(out var x) { M(out var y); } => M(out var z); C (out int x){x=1;} void M (out int x){x=1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(out var x)", initializerSyntax.ToString()); compilation.VerifyOperationTree(initializerSyntax, expectedOperationTree: @" IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation initializerOperation = model.GetOperation(initializerSyntax); Assert.Equal(OperationKind.ExpressionStatement, initializerOperation.Parent.Kind); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{ M(out var y); }", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Equal(OperationKind.ConstructorBody, blockBodyOperation.Parent.Kind); Assert.Same(initializerOperation.Parent.Parent, blockBodyOperation.Parent); Assert.Null(blockBodyOperation.Parent.Parent); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Same(blockBodyOperation.Parent, model.GetOperation(expressionBodySyntax).Parent); var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<ConstructorDeclarationSyntax>().First(); Assert.Same(blockBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null, IsInvalid) (Syntax: 'C() : this( ... out var z);') Locals: Local_1: System.Int32 x Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Expression: IInvocationOperation ( C..ctor(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: ': this(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: ': this(out var x)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ M(out var y); }') Locals: Local_1: System.Int32 y IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(out var y);') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var z)') Expression: IInvocationOperation ( void C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void MethodBodyOperation() { var text = @" public class C { int P { get {return M(out var x);} => M(out var y); } => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var expressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var y)", expressionBodySyntax.ToString()); compilation.VerifyOperationTree(expressionBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation expressionBodyOperation = model.GetOperation(expressionBodySyntax); Assert.Equal(OperationKind.MethodBody, expressionBodyOperation.Parent.Kind); Assert.Null(expressionBodyOperation.Parent.Parent); var blockBodySyntax = tree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First(); Assert.Equal("{return M(out var x);}", blockBodySyntax.ToString()); compilation.VerifyOperationTree(blockBodySyntax, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); IOperation blockBodyOperation = model.GetOperation(blockBodySyntax); Assert.Same(expressionBodyOperation.Parent, blockBodyOperation.Parent); var propertyExpressionBodySyntax = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().ElementAt(1); Assert.Equal("=> M(out var z)", propertyExpressionBodySyntax.ToString()); Assert.Null(model.GetOperation(propertyExpressionBodySyntax)); // https://github.com/dotnet/roslyn/issues/24900 var declarationSyntax = tree.GetRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>().Single(); Assert.Same(expressionBodyOperation.Parent, model.GetOperation(declarationSyntax)); compilation.VerifyOperationTree(declarationSyntax, expectedOperationTree: @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'get {return ... out var y);') BlockBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{return M(out var x);}') Locals: Local_1: System.Int32 x IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return M(out var x);') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var x)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var x') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x') ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ExpressionBody: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> M(out var y)') Locals: Local_1: System.Int32 y IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'M(out var y)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M(out var y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out var y') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var y') ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void PropertyExpressionBodyOperation() { var text = @" public class C { int P => M(out var z); int M (out int x){x=1; return 1;} } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node3 = tree.GetRoot().DescendantNodes().OfType<ArrowExpressionClauseSyntax>().First(); Assert.Equal("=> M(out var z)", node3.ToString()); compilation.VerifyOperationTree(node3, expectedOperationTree: @" IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '=> M(out var z)') Locals: Local_1: System.Int32 z IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'M(out var z)') ReturnedValue: IInvocationOperation ( System.Int32 C.M(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M(out var z)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var z') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var z') ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(node3).Parent); } [Fact] public void OutVarInConstructorUsedInObjectInitializer() { var source = @" public class C { public int Number { get; set; } public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { Number = i }; System.Console.WriteLine(c.Number); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] public void OutVarInConstructorUsedInCollectionInitializer() { var source = @" public class C : System.Collections.Generic.List<int> { public C(out int n) { n = 1; } public static void Main() { C c = new C(out var i) { i, i, i }; System.Console.WriteLine(c[0]); } } "; CompileAndVerify(source, expectedOutput: @"1"); } [Fact] [WorkItem(49997, "https://github.com/dotnet/roslyn/issues/49997")] public void Issue49997() { var text = @" public class Cls { public static void Main() { if () .Test1().Test2(out var x1).Test3(); } } static class Ext { public static void Test3(this Cls x) {} } "; var compilation = CreateCompilation(text); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test3").Last(); Assert.True(model.GetSymbolInfo(node).IsEmpty); } } internal static class OutVarTestsExtensions { internal static SingleVariableDesignationSyntax VariableDesignation(this DeclarationExpressionSyntax self) { return (SingleVariableDesignationSyntax)self.Designation; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Scripting/Core/ScriptState.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.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = value; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/Core/Portable/Options/IOptionPersisterProvider.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Options { internal interface IOptionPersisterProvider { /// <summary> /// Gets the <see cref="IOptionPersister"/>. If the persister does not already exist, it is created. /// </summary> /// <remarks> /// This method is safe for concurrent use from any thread. No guarantees are made regarding the use of the UI /// thread. /// </remarks> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> /// <returns>The option persister.</returns> ValueTask<IOptionPersister> GetOrCreatePersisterAsync(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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Options { internal interface IOptionPersisterProvider { /// <summary> /// Gets the <see cref="IOptionPersister"/>. If the persister does not already exist, it is created. /// </summary> /// <remarks> /// This method is safe for concurrent use from any thread. No guarantees are made regarding the use of the UI /// thread. /// </remarks> /// <param name="cancellationToken">A cancellation token the operation may observe.</param> /// <returns>The option persister.</returns> ValueTask<IOptionPersister> GetOrCreatePersisterAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/NullableHelpers/NullableExtensions.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. namespace Microsoft.CodeAnalysis { internal static partial class NullableExtensions { public static ITypeSymbol? GetConvertedTypeWithAnnotatedNullability(this TypeInfo typeInfo) => typeInfo.ConvertedType?.WithNullableAnnotation(typeInfo.ConvertedNullability.Annotation); public static ITypeSymbol? GetTypeWithAnnotatedNullability(this TypeInfo typeInfo) => typeInfo.Type?.WithNullableAnnotation(typeInfo.Nullability.Annotation); } }
// 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 { internal static partial class NullableExtensions { public static ITypeSymbol? GetConvertedTypeWithAnnotatedNullability(this TypeInfo typeInfo) => typeInfo.ConvertedType?.WithNullableAnnotation(typeInfo.ConvertedNullability.Annotation); public static ITypeSymbol? GetTypeWithAnnotatedNullability(this TypeInfo typeInfo) => typeInfo.Type?.WithNullableAnnotation(typeInfo.Nullability.Annotation); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedMember.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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedMember { internal abstract TEmbeddedTypesManager TypeManager { get; } } internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference where TMember : TSymbol, Cci.ITypeMemberReference { protected readonly TMember UnderlyingSymbol; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedMember(TMember underlyingSymbol) { this.UnderlyingSymbol = underlyingSymbol; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return null; } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics)); } } return builder.ToImmutableAndFree(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { throw ExceptionUtilities.Unreachable; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
// 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedMember { internal abstract TEmbeddedTypesManager TypeManager { get; } } internal abstract class CommonEmbeddedMember<TMember> : CommonEmbeddedMember, Cci.IReference where TMember : TSymbol, Cci.ITypeMemberReference { protected readonly TMember UnderlyingSymbol; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedMember(TMember underlyingSymbol) { this.UnderlyingSymbol = underlyingSymbol; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); protected virtual TAttributeData PortAttributeIfNeedTo(TAttributeData attrData, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return null; } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (TypeManager.IsTargetAttribute(UnderlyingSymbol, attrData, AttributeDescription.DispIdAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DispIdAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { builder.AddOptional(PortAttributeIfNeedTo(attrData, syntaxNodeOpt, diagnostics)); } } return builder.ToImmutableAndFree(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { throw ExceptionUtilities.Unreachable; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/Syntax/CommonSyntaxNodeRemover.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; namespace Microsoft.CodeAnalysis.Syntax { internal static class CommonSyntaxNodeRemover { public static void GetSeparatorInfo( SyntaxNodeOrTokenList nodesAndSeparators, int nodeIndex, int endOfLineKind, out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode) { // remove preceding separator if any, except for the case where // the following separator immediately touches the item in the list // and is followed by a newline. // // In that case, we consider the next token to be more closely // associated with the item, and it should be removed. // // For example, if you have: // // Goo(a, // a stuff // b, // b stuff // c); // // If we're removing 'b', we should remove the comma after it. // // If there is no next comma, or the next comma is not on the // same line, then just remove the preceding comma if there is // one. If there is no next or previous comma there's nothing // in the list that needs to be fixed up. var node = nodesAndSeparators[nodeIndex].AsNode(); Debug.Assert(node is object); nextTokenIsSeparator = nodeIndex + 1 < nodesAndSeparators.Count && nodesAndSeparators[nodeIndex + 1].IsToken; nextSeparatorBelongsToNode = nextTokenIsSeparator && nodesAndSeparators[nodeIndex + 1].AsToken() is var nextSeparator && !nextSeparator.HasLeadingTrivia && !ContainsEndOfLine(node.GetTrailingTrivia(), endOfLineKind) && ContainsEndOfLine(nextSeparator.TrailingTrivia, endOfLineKind); } private static bool ContainsEndOfLine(SyntaxTriviaList triviaList, int endOfLineKind) => triviaList.IndexOf(endOfLineKind) >= 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.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax { internal static class CommonSyntaxNodeRemover { public static void GetSeparatorInfo( SyntaxNodeOrTokenList nodesAndSeparators, int nodeIndex, int endOfLineKind, out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode) { // remove preceding separator if any, except for the case where // the following separator immediately touches the item in the list // and is followed by a newline. // // In that case, we consider the next token to be more closely // associated with the item, and it should be removed. // // For example, if you have: // // Goo(a, // a stuff // b, // b stuff // c); // // If we're removing 'b', we should remove the comma after it. // // If there is no next comma, or the next comma is not on the // same line, then just remove the preceding comma if there is // one. If there is no next or previous comma there's nothing // in the list that needs to be fixed up. var node = nodesAndSeparators[nodeIndex].AsNode(); Debug.Assert(node is object); nextTokenIsSeparator = nodeIndex + 1 < nodesAndSeparators.Count && nodesAndSeparators[nodeIndex + 1].IsToken; nextSeparatorBelongsToNode = nextTokenIsSeparator && nodesAndSeparators[nodeIndex + 1].AsToken() is var nextSeparator && !nextSeparator.HasLeadingTrivia && !ContainsEndOfLine(node.GetTrailingTrivia(), endOfLineKind) && ContainsEndOfLine(nextSeparator.TrailingTrivia, endOfLineKind); } private static bool ContainsEndOfLine(SyntaxTriviaList triviaList, int endOfLineKind) => triviaList.IndexOf(endOfLineKind) >= 0; } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/TextViewWindow_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 Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public abstract partial class TextViewWindow_OutOfProc : OutOfProcComponent { public Verifier<TextViewWindow_OutOfProc> Verify { get; } internal readonly TextViewWindow_InProc _textViewWindowInProc; private readonly VisualStudioInstance _instance; internal TextViewWindow_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _textViewWindowInProc = CreateInProcComponent(visualStudioInstance); _instance = visualStudioInstance; Verify = new Verifier<TextViewWindow_OutOfProc>(this, visualStudioInstance); } internal abstract TextViewWindow_InProc CreateInProcComponent(VisualStudioInstance visualStudioInstance); public int GetCaretPosition() => _textViewWindowInProc.GetCaretPosition(); public int GetCaretColumn() => _textViewWindowInProc.GetCaretColumn(); public string[] GetCompletionItems() { WaitForCompletionSet(); return _textViewWindowInProc.GetCompletionItems(); } public int GetVisibleColumnCount() => _textViewWindowInProc.GetVisibleColumnCount(); public void PlaceCaret( string marker, int charsOffset = 0, int occurrence = 0, bool extendSelection = false, bool selectBlock = false) => _textViewWindowInProc.PlaceCaret( marker, charsOffset, occurrence, extendSelection, selectBlock); public string[] GetCurrentClassifications() => _textViewWindowInProc.GetCurrentClassifications(); public string GetQuickInfo() => _textViewWindowInProc.GetQuickInfo(); public void VerifyTags(string tagTypeName, int expectedCount) => _textViewWindowInProc.VerifyTags(tagTypeName, expectedCount); public void ShowLightBulb() => _textViewWindowInProc.ShowLightBulb(); public void WaitForLightBulbSession() => _textViewWindowInProc.WaitForLightBulbSession(); public bool IsLightBulbSessionExpanded() => _textViewWindowInProc.IsLightBulbSessionExpanded(); public void DismissLightBulbSession() => _textViewWindowInProc.DismissLightBulbSession(); public void DismissCompletionSessions() { WaitForCompletionSet(); _textViewWindowInProc.DismissCompletionSessions(); } public string[] GetLightBulbActions() => _textViewWindowInProc.GetLightBulbActions(); public bool ApplyLightBulbAction(string action, FixAllScope? fixAllScope, bool blockUntilComplete = true) => _textViewWindowInProc.ApplyLightBulbAction(action, fixAllScope, blockUntilComplete); public void InvokeCompletionList() { _instance.ExecuteCommand(WellKnownCommandNames.Edit_ListMembers); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.CompletionSet); } public void InvokeCodeActionList() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); ShowLightBulb(); WaitForLightBulbSession(); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); } /// <summary> /// Invokes the lightbulb without waiting for diagnostics /// Compare to <see cref="InvokeCodeActionList"/> /// </summary> public void InvokeCodeActionListWithoutWaiting() { ShowLightBulb(); WaitForLightBulbSession(); } public void InvokeQuickInfo() => _textViewWindowInProc.InvokeQuickInfo(); } }
// 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.CodeFixes; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public abstract partial class TextViewWindow_OutOfProc : OutOfProcComponent { public Verifier<TextViewWindow_OutOfProc> Verify { get; } internal readonly TextViewWindow_InProc _textViewWindowInProc; private readonly VisualStudioInstance _instance; internal TextViewWindow_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _textViewWindowInProc = CreateInProcComponent(visualStudioInstance); _instance = visualStudioInstance; Verify = new Verifier<TextViewWindow_OutOfProc>(this, visualStudioInstance); } internal abstract TextViewWindow_InProc CreateInProcComponent(VisualStudioInstance visualStudioInstance); public int GetCaretPosition() => _textViewWindowInProc.GetCaretPosition(); public int GetCaretColumn() => _textViewWindowInProc.GetCaretColumn(); public string[] GetCompletionItems() { WaitForCompletionSet(); return _textViewWindowInProc.GetCompletionItems(); } public int GetVisibleColumnCount() => _textViewWindowInProc.GetVisibleColumnCount(); public void PlaceCaret( string marker, int charsOffset = 0, int occurrence = 0, bool extendSelection = false, bool selectBlock = false) => _textViewWindowInProc.PlaceCaret( marker, charsOffset, occurrence, extendSelection, selectBlock); public string[] GetCurrentClassifications() => _textViewWindowInProc.GetCurrentClassifications(); public string GetQuickInfo() => _textViewWindowInProc.GetQuickInfo(); public void VerifyTags(string tagTypeName, int expectedCount) => _textViewWindowInProc.VerifyTags(tagTypeName, expectedCount); public void ShowLightBulb() => _textViewWindowInProc.ShowLightBulb(); public void WaitForLightBulbSession() => _textViewWindowInProc.WaitForLightBulbSession(); public bool IsLightBulbSessionExpanded() => _textViewWindowInProc.IsLightBulbSessionExpanded(); public void DismissLightBulbSession() => _textViewWindowInProc.DismissLightBulbSession(); public void DismissCompletionSessions() { WaitForCompletionSet(); _textViewWindowInProc.DismissCompletionSessions(); } public string[] GetLightBulbActions() => _textViewWindowInProc.GetLightBulbActions(); public bool ApplyLightBulbAction(string action, FixAllScope? fixAllScope, bool blockUntilComplete = true) => _textViewWindowInProc.ApplyLightBulbAction(action, fixAllScope, blockUntilComplete); public void InvokeCompletionList() { _instance.ExecuteCommand(WellKnownCommandNames.Edit_ListMembers); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.CompletionSet); } public void InvokeCodeActionList() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); ShowLightBulb(); WaitForLightBulbSession(); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LightBulb); } /// <summary> /// Invokes the lightbulb without waiting for diagnostics /// Compare to <see cref="InvokeCodeActionList"/> /// </summary> public void InvokeCodeActionListWithoutWaiting() { ShowLightBulb(); WaitForLightBulbSession(); } public void InvokeQuickInfo() => _textViewWindowInProc.InvokeQuickInfo(); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSimpleProgramEntryPointSymbol.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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedSimpleProgramEntryPointSymbol : SourceMemberMethodSymbol { /// <summary> /// The corresponding <see cref="SingleTypeDeclaration"/>. /// </summary> private readonly SingleTypeDeclaration _declaration; private readonly TypeSymbol _returnType; private readonly ImmutableArray<ParameterSymbol> _parameters; private WeakReference<ExecutableCodeBinder>? _weakBodyBinder; private WeakReference<ExecutableCodeBinder>? _weakIgnoreAccessibilityBodyBinder; internal SynthesizedSimpleProgramEntryPointSymbol(SourceMemberContainerTypeSymbol containingType, SingleTypeDeclaration declaration, BindingDiagnosticBag diagnostics) : base(containingType, syntaxReferenceOpt: declaration.SyntaxReference, ImmutableArray.Create(declaration.SyntaxReference.GetLocation()), isIterator: declaration.IsIterator) { Debug.Assert(declaration.SyntaxReference.GetSyntax() is CompilationUnitSyntax); _declaration = declaration; bool hasAwait = declaration.HasAwaitExpressions; bool hasReturnWithExpression = declaration.HasReturnWithExpression; CSharpCompilation compilation = containingType.DeclaringCompilation; switch (hasAwait, hasReturnWithExpression) { case (true, false): _returnType = Binder.GetWellKnownType(compilation, WellKnownType.System_Threading_Tasks_Task, diagnostics, NoLocation.Singleton); break; case (false, false): _returnType = Binder.GetSpecialType(compilation, SpecialType.System_Void, NoLocation.Singleton, diagnostics); break; case (true, true): _returnType = Binder.GetWellKnownType(compilation, WellKnownType.System_Threading_Tasks_Task_T, diagnostics, NoLocation.Singleton). Construct(Binder.GetSpecialType(compilation, SpecialType.System_Int32, NoLocation.Singleton, diagnostics)); break; case (false, true): _returnType = Binder.GetSpecialType(compilation, SpecialType.System_Int32, NoLocation.Singleton, diagnostics); break; } bool isNullableAnalysisEnabled = IsNullableAnalysisEnabled(compilation, CompilationUnit); this.MakeFlags( MethodKind.Ordinary, DeclarationModifiers.Static | DeclarationModifiers.Private | (hasAwait ? DeclarationModifiers.Async : DeclarationModifiers.None), returnsVoid: !hasAwait && !hasReturnWithExpression, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: false); _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create( ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_String, NoLocation.Singleton, diagnostics)))), 0, RefKind.None, "args")); } internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation, CompilationUnitSyntax compilationUnit, bool fallbackToMainEntryPoint) { var type = GetSimpleProgramNamedTypeSymbol(compilation); if (type is null) { return null; } ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> entryPoints = type.GetSimpleProgramEntryPoints(); foreach (var entryPoint in entryPoints) { if (entryPoint.SyntaxTree == compilationUnit.SyntaxTree && entryPoint.SyntaxNode == compilationUnit) { return entryPoint; } } return fallbackToMainEntryPoint ? entryPoints[0] : null; } internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation) { return GetSimpleProgramNamedTypeSymbol(compilation)?.GetSimpleProgramEntryPoints().First(); } private static SourceNamedTypeSymbol? GetSimpleProgramNamedTypeSymbol(CSharpCompilation compilation) { return compilation.SourceModule.GlobalNamespace.GetTypeMembers(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName).OfType<SourceNamedTypeSymbol>().SingleOrDefault(s => s.IsSimpleProgram); } public override string Name { get { return WellKnownMemberNames.TopLevelStatementsEntryPointMethodName; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } public override bool IsVararg { get { return false; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal override int ParameterCount { get { return 1; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override bool IsImplicitlyDeclared { get { return false; } } internal sealed override bool GenerateDebugInfo { get { return true; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { } internal override bool IsExpressionBodied => false; public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected override object MethodChecksLockObject => _declaration; internal CompilationUnitSyntax CompilationUnit => (CompilationUnitSyntax)SyntaxNode; internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) { return GetBodyBinder(ignoreAccessibility); } private ExecutableCodeBinder CreateBodyBinder(bool ignoreAccessibility) { CSharpCompilation compilation = DeclaringCompilation; Binder result = new BuckStopsHereBinder(compilation); var globalNamespace = compilation.GlobalNamespace; var declaringSymbol = (SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace; var syntaxNode = SyntaxNode; result = WithExternAndUsingAliasesBinder.Create(declaringSymbol, syntaxNode, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, syntaxNode, result)); result = new InContainerBinder(globalNamespace, result); result = new InContainerBinder(ContainingType, result); result = new InMethodBinder(this, result); result = result.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); return new ExecutableCodeBinder(syntaxNode, this, result); } internal ExecutableCodeBinder GetBodyBinder(bool ignoreAccessibility) { ref WeakReference<ExecutableCodeBinder>? weakBinder = ref ignoreAccessibility ? ref _weakIgnoreAccessibilityBodyBinder : ref _weakBodyBinder; while (true) { var previousWeakReference = weakBinder; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out ExecutableCodeBinder? previousBinder)) { return previousBinder; } ExecutableCodeBinder newBinder = CreateBodyBinder(ignoreAccessibility); if (Interlocked.CompareExchange(ref weakBinder, new WeakReference<ExecutableCodeBinder>(newBinder), previousWeakReference) == previousWeakReference) { return newBinder; } } } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { if (_declaration.SyntaxReference.SyntaxTree == tree) { if (!definedWithinSpan.HasValue) { return true; } else { var span = definedWithinSpan.GetValueOrDefault(); foreach (var global in ((CompilationUnitSyntax)tree.GetRoot(cancellationToken)).Members.OfType<GlobalStatementSyntax>()) { cancellationToken.ThrowIfCancellationRequested(); if (global.Span.IntersectsWith(span)) { return true; } } } } return false; } public SyntaxNode ReturnTypeSyntax => CompilationUnit.Members.First(m => m.Kind() == SyntaxKind.GlobalStatement); private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation, CompilationUnitSyntax syntax) { foreach (var member in syntax.Members) { if (member.Kind() == SyntaxKind.GlobalStatement && compilation.IsNullableAnalysisEnabledIn(member)) { 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; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SynthesizedSimpleProgramEntryPointSymbol : SourceMemberMethodSymbol { /// <summary> /// The corresponding <see cref="SingleTypeDeclaration"/>. /// </summary> private readonly SingleTypeDeclaration _declaration; private readonly TypeSymbol _returnType; private readonly ImmutableArray<ParameterSymbol> _parameters; private WeakReference<ExecutableCodeBinder>? _weakBodyBinder; private WeakReference<ExecutableCodeBinder>? _weakIgnoreAccessibilityBodyBinder; internal SynthesizedSimpleProgramEntryPointSymbol(SourceMemberContainerTypeSymbol containingType, SingleTypeDeclaration declaration, BindingDiagnosticBag diagnostics) : base(containingType, syntaxReferenceOpt: declaration.SyntaxReference, ImmutableArray.Create(declaration.SyntaxReference.GetLocation()), isIterator: declaration.IsIterator) { Debug.Assert(declaration.SyntaxReference.GetSyntax() is CompilationUnitSyntax); _declaration = declaration; bool hasAwait = declaration.HasAwaitExpressions; bool hasReturnWithExpression = declaration.HasReturnWithExpression; CSharpCompilation compilation = containingType.DeclaringCompilation; switch (hasAwait, hasReturnWithExpression) { case (true, false): _returnType = Binder.GetWellKnownType(compilation, WellKnownType.System_Threading_Tasks_Task, diagnostics, NoLocation.Singleton); break; case (false, false): _returnType = Binder.GetSpecialType(compilation, SpecialType.System_Void, NoLocation.Singleton, diagnostics); break; case (true, true): _returnType = Binder.GetWellKnownType(compilation, WellKnownType.System_Threading_Tasks_Task_T, diagnostics, NoLocation.Singleton). Construct(Binder.GetSpecialType(compilation, SpecialType.System_Int32, NoLocation.Singleton, diagnostics)); break; case (false, true): _returnType = Binder.GetSpecialType(compilation, SpecialType.System_Int32, NoLocation.Singleton, diagnostics); break; } bool isNullableAnalysisEnabled = IsNullableAnalysisEnabled(compilation, CompilationUnit); this.MakeFlags( MethodKind.Ordinary, DeclarationModifiers.Static | DeclarationModifiers.Private | (hasAwait ? DeclarationModifiers.Async : DeclarationModifiers.None), returnsVoid: !hasAwait && !hasReturnWithExpression, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers: false); _parameters = ImmutableArray.Create(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create( ArrayTypeSymbol.CreateCSharpArray(compilation.Assembly, TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_String, NoLocation.Singleton, diagnostics)))), 0, RefKind.None, "args")); } internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation, CompilationUnitSyntax compilationUnit, bool fallbackToMainEntryPoint) { var type = GetSimpleProgramNamedTypeSymbol(compilation); if (type is null) { return null; } ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> entryPoints = type.GetSimpleProgramEntryPoints(); foreach (var entryPoint in entryPoints) { if (entryPoint.SyntaxTree == compilationUnit.SyntaxTree && entryPoint.SyntaxNode == compilationUnit) { return entryPoint; } } return fallbackToMainEntryPoint ? entryPoints[0] : null; } internal static SynthesizedSimpleProgramEntryPointSymbol? GetSimpleProgramEntryPoint(CSharpCompilation compilation) { return GetSimpleProgramNamedTypeSymbol(compilation)?.GetSimpleProgramEntryPoints().First(); } private static SourceNamedTypeSymbol? GetSimpleProgramNamedTypeSymbol(CSharpCompilation compilation) { return compilation.SourceModule.GlobalNamespace.GetTypeMembers(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName).OfType<SourceNamedTypeSymbol>().SingleOrDefault(s => s.IsSimpleProgram); } public override string Name { get { return WellKnownMemberNames.TopLevelStatementsEntryPointMethodName; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } public override bool IsVararg { get { return false; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal override int ParameterCount { get { return 1; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override bool IsImplicitlyDeclared { get { return false; } } internal sealed override bool GenerateDebugInfo { get { return true; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return localPosition; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { } internal override bool IsExpressionBodied => false; public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; protected override object MethodChecksLockObject => _declaration; internal CompilationUnitSyntax CompilationUnit => (CompilationUnitSyntax)SyntaxNode; internal override ExecutableCodeBinder TryGetBodyBinder(BinderFactory? binderFactoryOpt = null, bool ignoreAccessibility = false) { return GetBodyBinder(ignoreAccessibility); } private ExecutableCodeBinder CreateBodyBinder(bool ignoreAccessibility) { CSharpCompilation compilation = DeclaringCompilation; Binder result = new BuckStopsHereBinder(compilation); var globalNamespace = compilation.GlobalNamespace; var declaringSymbol = (SourceNamespaceSymbol)compilation.SourceModule.GlobalNamespace; var syntaxNode = SyntaxNode; result = WithExternAndUsingAliasesBinder.Create(declaringSymbol, syntaxNode, WithUsingNamespacesAndTypesBinder.Create(declaringSymbol, syntaxNode, result)); result = new InContainerBinder(globalNamespace, result); result = new InContainerBinder(ContainingType, result); result = new InMethodBinder(this, result); result = result.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); return new ExecutableCodeBinder(syntaxNode, this, result); } internal ExecutableCodeBinder GetBodyBinder(bool ignoreAccessibility) { ref WeakReference<ExecutableCodeBinder>? weakBinder = ref ignoreAccessibility ? ref _weakIgnoreAccessibilityBodyBinder : ref _weakBodyBinder; while (true) { var previousWeakReference = weakBinder; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out ExecutableCodeBinder? previousBinder)) { return previousBinder; } ExecutableCodeBinder newBinder = CreateBodyBinder(ignoreAccessibility); if (Interlocked.CompareExchange(ref weakBinder, new WeakReference<ExecutableCodeBinder>(newBinder), previousWeakReference) == previousWeakReference) { return newBinder; } } } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { if (_declaration.SyntaxReference.SyntaxTree == tree) { if (!definedWithinSpan.HasValue) { return true; } else { var span = definedWithinSpan.GetValueOrDefault(); foreach (var global in ((CompilationUnitSyntax)tree.GetRoot(cancellationToken)).Members.OfType<GlobalStatementSyntax>()) { cancellationToken.ThrowIfCancellationRequested(); if (global.Span.IntersectsWith(span)) { return true; } } } } return false; } public SyntaxNode ReturnTypeSyntax => CompilationUnit.Members.First(m => m.Kind() == SyntaxKind.GlobalStatement); private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation, CompilationUnitSyntax syntax) { foreach (var member in syntax.Members) { if (member.Kind() == SyntaxKind.GlobalStatement && compilation.IsNullableAnalysisEnabledIn(member)) { return true; } } return false; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/Core/Portable/Workspace/Solution/TextDifferenceTypes.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 { /// <summary> /// A bitwise combination of the enumeration values to use when computing differences with /// <see cref="IDocumentTextDifferencingService" />. /// </summary> /// <remarks> /// Since computing differences can be slow with large data sets, you should not use the Character type /// unless the given text is relatively small. /// </remarks> [Flags] internal enum TextDifferenceTypes { /// <summary> /// Compute the line difference. /// </summary> Line = 1, /// <summary> /// Compute the word difference. /// </summary> Word = 2, /// <summary> /// Compute the character difference. /// </summary> Character = 4 } }
// 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 { /// <summary> /// A bitwise combination of the enumeration values to use when computing differences with /// <see cref="IDocumentTextDifferencingService" />. /// </summary> /// <remarks> /// Since computing differences can be slow with large data sets, you should not use the Character type /// unless the given text is relatively small. /// </remarks> [Flags] internal enum TextDifferenceTypes { /// <summary> /// Compute the line difference. /// </summary> Line = 1, /// <summary> /// Compute the word difference. /// </summary> Word = 2, /// <summary> /// Compute the character difference. /// </summary> Character = 4 } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/CodeGen/DebugId.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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Unique identification of an emitted entity (method, lambda, closure) used for debugging purposes (EnC). /// </summary> /// <remarks> /// When used for a synthesized method the ordinal and generation numbers are included its name. /// For user defined methods the ordinal is included in Custom Debug Information record attached to the method. /// </remarks> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct DebugId : IEquatable<DebugId> { public const int UndefinedOrdinal = -1; /// <summary> /// The index of the method in member list of the containing type, or <see cref="UndefinedOrdinal"/> if undefined. /// </summary> public readonly int Ordinal; /// <summary> /// The EnC generation the method was defined in (0 is the baseline build). /// </summary> public readonly int Generation; public DebugId(int ordinal, int generation) { Debug.Assert(ordinal >= 0 || ordinal == UndefinedOrdinal); Debug.Assert(generation >= 0); this.Ordinal = ordinal; this.Generation = generation; } public bool Equals(DebugId other) { return this.Ordinal == other.Ordinal && this.Generation == other.Generation; } public override bool Equals(object? obj) { return obj is DebugId && Equals((DebugId)obj); } public override int GetHashCode() { return Hash.Combine(this.Ordinal, this.Generation); } internal string GetDebuggerDisplay() { return (Generation > 0) ? $"{Ordinal}#{Generation}" : Ordinal.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.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Unique identification of an emitted entity (method, lambda, closure) used for debugging purposes (EnC). /// </summary> /// <remarks> /// When used for a synthesized method the ordinal and generation numbers are included its name. /// For user defined methods the ordinal is included in Custom Debug Information record attached to the method. /// </remarks> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal struct DebugId : IEquatable<DebugId> { public const int UndefinedOrdinal = -1; /// <summary> /// The index of the method in member list of the containing type, or <see cref="UndefinedOrdinal"/> if undefined. /// </summary> public readonly int Ordinal; /// <summary> /// The EnC generation the method was defined in (0 is the baseline build). /// </summary> public readonly int Generation; public DebugId(int ordinal, int generation) { Debug.Assert(ordinal >= 0 || ordinal == UndefinedOrdinal); Debug.Assert(generation >= 0); this.Ordinal = ordinal; this.Generation = generation; } public bool Equals(DebugId other) { return this.Ordinal == other.Ordinal && this.Generation == other.Generation; } public override bool Equals(object? obj) { return obj is DebugId && Equals((DebugId)obj); } public override int GetHashCode() { return Hash.Combine(this.Ordinal, this.Generation); } internal string GetDebuggerDisplay() { return (Generation > 0) ? $"{Ordinal}#{Generation}" : Ordinal.ToString(); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/Completion/Utilities.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.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { internal static class Utilities { public static TextChange Collapse(SourceText newText, ImmutableArray<TextChange> changes) { if (changes.Length == 0) { return new TextChange(new TextSpan(0, 0), ""); } else if (changes.Length == 1) { return changes[0]; } // The span we want to replace goes from the start of the first span to the end of // the last span. var totalOldSpan = TextSpan.FromBounds(changes.First().Span.Start, changes.Last().Span.End); // We figure out the text we're replacing with by actually just figuring out the // new span in the newText and grabbing the text out of that. The newSpan will // start from the same position as the oldSpan, but it's length will be the old // span's length + all the deltas we accumulate through each text change. i.e. // if the first change adds 2 characters and the second change adds 4, then // the newSpan will be 2+4=6 characters longer than the old span. var sumOfDeltas = changes.Sum(c => c.NewText.Length - c.Span.Length); var totalNewSpan = new TextSpan(totalOldSpan.Start, totalOldSpan.Length + sumOfDeltas); return new TextChange(totalOldSpan, newText.ToString(totalNewSpan)); } // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. // We check both the display text and the display text prefix to account for IntelliCode item providers // that may be using the prefix to include the ★. internal static bool IsPreferredItem(this CompletionItem completionItem) => completionItem.DisplayText.StartsWith("★") || completionItem.DisplayTextPrefix.StartsWith("★"); } }
// 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.Linq; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { internal static class Utilities { public static TextChange Collapse(SourceText newText, ImmutableArray<TextChange> changes) { if (changes.Length == 0) { return new TextChange(new TextSpan(0, 0), ""); } else if (changes.Length == 1) { return changes[0]; } // The span we want to replace goes from the start of the first span to the end of // the last span. var totalOldSpan = TextSpan.FromBounds(changes.First().Span.Start, changes.Last().Span.End); // We figure out the text we're replacing with by actually just figuring out the // new span in the newText and grabbing the text out of that. The newSpan will // start from the same position as the oldSpan, but it's length will be the old // span's length + all the deltas we accumulate through each text change. i.e. // if the first change adds 2 characters and the second change adds 4, then // the newSpan will be 2+4=6 characters longer than the old span. var sumOfDeltas = changes.Sum(c => c.NewText.Length - c.Span.Length); var totalNewSpan = new TextSpan(totalOldSpan.Start, totalOldSpan.Length + sumOfDeltas); return new TextChange(totalOldSpan, newText.ToString(totalNewSpan)); } // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. // We check both the display text and the display text prefix to account for IntelliCode item providers // that may be using the prefix to include the ★. internal static bool IsPreferredItem(this CompletionItem completionItem) => completionItem.DisplayText.StartsWith("★") || completionItem.DisplayTextPrefix.StartsWith("★"); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/Core/Portable/Workspace/Host/Metadata/IAnalyzerAssemblyLoaderProvider.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. namespace Microsoft.CodeAnalysis.Host { internal interface IAnalyzerAssemblyLoaderProvider : IWorkspaceService { IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options); } }
// 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.Host { internal interface IAnalyzerAssemblyLoaderProvider : IWorkspaceService { IAnalyzerAssemblyLoader GetLoader(in AnalyzerAssemblyLoaderOptions options); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/Intents/IntentProviderAttribute.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.Composition; namespace Microsoft.CodeAnalysis.Features.Intents { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal class IntentProviderAttribute : ExportAttribute, IIntentProviderMetadata { public string IntentName { get; } public string LanguageName { get; } public IntentProviderAttribute(string intentName, string languageName) : base(typeof(IIntentProvider)) { IntentName = intentName; LanguageName = languageName; } } }
// 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.Composition; namespace Microsoft.CodeAnalysis.Features.Intents { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] internal class IntentProviderAttribute : ExportAttribute, IIntentProviderMetadata { public string IntentName { get; } public string LanguageName { get; } public IntentProviderAttribute(string intentName, string languageName) : base(typeof(IIntentProvider)) { IntentName = intentName; LanguageName = languageName; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/CSharp/Portable/SignatureHelp/ElementAccessExpressionSignatureHelpProvider.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ElementAccessExpressionSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => IsTriggerCharacterInternal(ch); private static bool IsTriggerCharacterInternal(char ch) => ch == '[' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ']'; private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || ConditionalAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace); } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetElementAccessExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var expression, out var openBrace)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); // goo?[$$] if (expressionSymbol is INamedTypeSymbol namedType) { if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && expression.IsKind(SyntaxKind.NullableType) && expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType)) { // Speculatively bind the type part of the nullable as an expression var nullableTypeSyntax = (NullableTypeSyntax)expression; var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression); expressionSymbol = speculativeBinding.GetAnySymbol(); expression = nullableTypeSyntax.ElementType; } } if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol) { return null; } if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out var indexers, out var expressionType) && !TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType)) { return null; } var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var accessibleIndexers = indexers.WhereAsArray( m => m.IsAccessibleWithin(within, throughType: expressionType)); if (!accessibleIndexers.Any()) { return null; } accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(semanticModel, expression.SpanStart); var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(expression, openBrace); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleIndexers.Select(p => Convert(p, openBrace, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem: null); } private static TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket) { if (openBracket.Parent is BracketedArgumentListSyntax) { if (expression.Parent is ConditionalAccessExpressionSyntax conditional) { return TextSpan.FromBounds(conditional.Span.Start, openBracket.FullSpan.End); } else { return CompleteElementAccessExpression.GetTextSpan(openBracket); } } else if (openBracket.Parent is ArrayRankSpecifierSyntax) { return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket); } throw ExceptionUtilities.Unreachable; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (!TryGetElementAccessExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression, out var openBracket) || currentSpan.Start != expression.SpanStart) { return null; } // If the user is actively typing, it's likely that we're in a broken state and the // syntax tree will be incorrect. Because of this we need to synthesize a new // bracketed argument list so we can correctly map the cursor to the current argument // and then we need to account for this and offset the position check accordingly. int offset; BracketedArgumentListSyntax argumentList; var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent!.ToString()); if (expression.Parent is ConditionalAccessExpressionSyntax) { // The typed code looks like: <expression>?[ var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList); var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding); offset = expression.SpanStart - conditionalAccessExpression.SpanStart; argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList; } else { // The typed code looks like: // <expression>[ // or // <identifier>?[ var elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList); offset = expression.SpanStart - elementAccessExpression.SpanStart; argumentList = elementAccessExpression.ArgumentList; } position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(argumentList, position); } private static bool TryGetComIndexers( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol? expressionType) { indexers = semanticModel.GetMemberGroup(expression, cancellationToken) .OfType<IPropertySymbol>() .ToImmutableArray(); if (indexers.Any() && expression is MemberAccessExpressionSyntax memberAccessExpression) { expressionType = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken).Type!; return true; } expressionType = null; return false; } private static bool TryGetIndexers( int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol? expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = ImmutableArray<IPropertySymbol>.Empty; return false; } if (expressionType is IErrorTypeSymbol errorType) { // If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so // we should then fall back to getting the actual symbol for the expression. expressionType = errorType.CandidateSymbols.FirstOrDefault().GetSymbolType() ?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer) .OfType<IPropertySymbol>() .ToImmutableArray(); return true; } private static SignatureHelpItem Convert( IPropertySymbol indexer, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem(indexer, semanticModel, position, anonymousTypeDisplayService, indexer.IsParams(), indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(indexer, position, semanticModel), GetSeparatorParts(), GetPostambleParts(), indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetPreambleParts( IPropertySymbol indexer, int position, SemanticModel semanticModel) { var result = new List<SymbolDisplayPart>(); if (indexer.ReturnsByRef) { result.Add(Keyword(SyntaxKind.RefKeyword)); result.Add(Space()); } else if (indexer.ReturnsByRefReadonly) { result.Add(Keyword(SyntaxKind.RefKeyword)); result.Add(Space()); result.Add(Keyword(SyntaxKind.ReadOnlyKeyword)); result.Add(Space()); } result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position)); result.Add(Space()); result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position)); if (indexer.Name != WellKnownMemberNames.Indexer) { result.Add(Punctuation(SyntaxKind.DotToken)); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name)); } result.Add(Punctuation(SyntaxKind.OpenBracketToken)); return result; } private static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseBracketToken)); } private static class CompleteElementAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static TextSpan GetTextSpan(SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax && (openBracket.Parent.Parent is ElementAccessExpressionSyntax || openBracket.Parent.Parent is ElementBindingExpressionSyntax)); return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ElementAccessExpressionSyntax elementAccessExpression)) { identifier = elementAccessExpression.Expression; openBrace = elementAccessExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default; return false; } } /// Error tolerance case for /// "goo[$$]" or "goo?[$$]" /// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression private static class IncompleteElementAccessExpression { internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token) { return node.RankSpecifiers.Span.Contains(token.SpanStart) && token != node.RankSpecifiers.First().CloseBracketToken; } internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is ArrayRankSpecifierSyntax; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax); return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ArrayTypeSyntax arrayTypeSyntax)) { identifier = arrayTypeSyntax.ElementType; openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken; return true; } identifier = null; openBrace = default; return false; } } /// Error tolerance case for /// "new String()?[$$]" /// which is parsed as a BracketedArgumentListSyntax parented by an ElementBindingExpressionSyntax parented by a ConditionalAccessExpressionSyntax private static class ConditionalAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementBindingExpressionSyntax && token.Parent.Parent.Parent is ConditionalAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementBindingExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ElementBindingExpressionSyntax elementBindingExpression)) { // Find the first conditional access expression that starts left of our open bracket var conditionalAccess = elementBindingExpression.FirstAncestorOrSelf<ConditionalAccessExpressionSyntax, ElementBindingExpressionSyntax>( (c, elementBindingExpression) => c.SpanStart < elementBindingExpression.SpanStart, elementBindingExpression)!; identifier = conditionalAccess.Expression; openBrace = elementBindingExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default; 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ElementAccessExpressionSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => IsTriggerCharacterInternal(ch); private static bool IsTriggerCharacterInternal(char ch) => ch == '[' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == ']'; private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || ConditionalAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace); } protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetElementAccessExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var expression, out var openBrace)) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); // goo?[$$] if (expressionSymbol is INamedTypeSymbol namedType) { if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && expression.IsKind(SyntaxKind.NullableType) && expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType)) { // Speculatively bind the type part of the nullable as an expression var nullableTypeSyntax = (NullableTypeSyntax)expression; var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression); expressionSymbol = speculativeBinding.GetAnySymbol(); expression = nullableTypeSyntax.ElementType; } } if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol) { return null; } if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out var indexers, out var expressionType) && !TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType)) { return null; } var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var accessibleIndexers = indexers.WhereAsArray( m => m.IsAccessibleWithin(within, throughType: expressionType)); if (!accessibleIndexers.Any()) { return null; } accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(semanticModel, expression.SpanStart); var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(expression, openBrace); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleIndexers.Select(p => Convert(p, openBrace, semanticModel, anonymousTypeDisplayService, documentationCommentFormattingService)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken), selectedItem: null); } private static TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket) { if (openBracket.Parent is BracketedArgumentListSyntax) { if (expression.Parent is ConditionalAccessExpressionSyntax conditional) { return TextSpan.FromBounds(conditional.Span.Start, openBracket.FullSpan.End); } else { return CompleteElementAccessExpression.GetTextSpan(openBracket); } } else if (openBracket.Parent is ArrayRankSpecifierSyntax) { return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket); } throw ExceptionUtilities.Unreachable; } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (!TryGetElementAccessExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression, out var openBracket) || currentSpan.Start != expression.SpanStart) { return null; } // If the user is actively typing, it's likely that we're in a broken state and the // syntax tree will be incorrect. Because of this we need to synthesize a new // bracketed argument list so we can correctly map the cursor to the current argument // and then we need to account for this and offset the position check accordingly. int offset; BracketedArgumentListSyntax argumentList; var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent!.ToString()); if (expression.Parent is ConditionalAccessExpressionSyntax) { // The typed code looks like: <expression>?[ var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList); var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding); offset = expression.SpanStart - conditionalAccessExpression.SpanStart; argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList; } else { // The typed code looks like: // <expression>[ // or // <identifier>?[ var elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList); offset = expression.SpanStart - elementAccessExpression.SpanStart; argumentList = elementAccessExpression.ArgumentList; } position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(argumentList, position); } private static bool TryGetComIndexers( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol? expressionType) { indexers = semanticModel.GetMemberGroup(expression, cancellationToken) .OfType<IPropertySymbol>() .ToImmutableArray(); if (indexers.Any() && expression is MemberAccessExpressionSyntax memberAccessExpression) { expressionType = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken).Type!; return true; } expressionType = null; return false; } private static bool TryGetIndexers( int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol? expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = ImmutableArray<IPropertySymbol>.Empty; return false; } if (expressionType is IErrorTypeSymbol errorType) { // If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so // we should then fall back to getting the actual symbol for the expression. expressionType = errorType.CandidateSymbols.FirstOrDefault().GetSymbolType() ?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer) .OfType<IPropertySymbol>() .ToImmutableArray(); return true; } private static SignatureHelpItem Convert( IPropertySymbol indexer, SyntaxToken openToken, SemanticModel semanticModel, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService) { var position = openToken.SpanStart; var item = CreateItem(indexer, semanticModel, position, anonymousTypeDisplayService, indexer.IsParams(), indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(indexer, position, semanticModel), GetSeparatorParts(), GetPostambleParts(), indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList()); return item; } private static IList<SymbolDisplayPart> GetPreambleParts( IPropertySymbol indexer, int position, SemanticModel semanticModel) { var result = new List<SymbolDisplayPart>(); if (indexer.ReturnsByRef) { result.Add(Keyword(SyntaxKind.RefKeyword)); result.Add(Space()); } else if (indexer.ReturnsByRefReadonly) { result.Add(Keyword(SyntaxKind.RefKeyword)); result.Add(Space()); result.Add(Keyword(SyntaxKind.ReadOnlyKeyword)); result.Add(Space()); } result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position)); result.Add(Space()); result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position)); if (indexer.Name != WellKnownMemberNames.Indexer) { result.Add(Punctuation(SyntaxKind.DotToken)); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name)); } result.Add(Punctuation(SyntaxKind.OpenBracketToken)); return result; } private static IList<SymbolDisplayPart> GetPostambleParts() { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseBracketToken)); } private static class CompleteElementAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static TextSpan GetTextSpan(SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax && (openBracket.Parent.Parent is ElementAccessExpressionSyntax || openBracket.Parent.Parent is ElementBindingExpressionSyntax)); return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ElementAccessExpressionSyntax elementAccessExpression)) { identifier = elementAccessExpression.Expression; openBrace = elementAccessExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default; return false; } } /// Error tolerance case for /// "goo[$$]" or "goo?[$$]" /// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression private static class IncompleteElementAccessExpression { internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token) { return node.RankSpecifiers.Span.Contains(token.SpanStart) && token != node.RankSpecifiers.First().CloseBracketToken; } internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is ArrayRankSpecifierSyntax; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax); return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ArrayTypeSyntax arrayTypeSyntax)) { identifier = arrayTypeSyntax.ElementType; openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken; return true; } identifier = null; openBrace = default; return false; } } /// Error tolerance case for /// "new String()?[$$]" /// which is parsed as a BracketedArgumentListSyntax parented by an ElementBindingExpressionSyntax parented by a ConditionalAccessExpressionSyntax private static class ConditionalAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementBindingExpressionSyntax && token.Parent.Parent.Parent is ConditionalAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementBindingExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, [NotNullWhen(true)] out ExpressionSyntax? identifier, out SyntaxToken openBrace) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out ElementBindingExpressionSyntax elementBindingExpression)) { // Find the first conditional access expression that starts left of our open bracket var conditionalAccess = elementBindingExpression.FirstAncestorOrSelf<ConditionalAccessExpressionSyntax, ElementBindingExpressionSyntax>( (c, elementBindingExpression) => c.SpanStart < elementBindingExpression.SpanStart, elementBindingExpression)!; identifier = conditionalAccess.Expression; openBrace = elementBindingExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default; return false; } } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/SpecialMembers.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.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class SpecialMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static SpecialMembers() { byte[] initializationBytes = new byte[] { // System_String__CtorSZArrayChar (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_String__ConcatStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Length (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Chars (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Format (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__Substring (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Double__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Double, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Single__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Single, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Delegate__Combine (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__Remove (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Decimal__Zero (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__MinusOne (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__One (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__CtorInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__CtorUInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__CtorUInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__CtorSingle (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Decimal__CtorDouble (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__CtorInt32Int32Int32BooleanByte (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Addition (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Subtraction (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Multiply (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Division (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Modulus (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_UnaryNegation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Increment (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Decrement (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__NegateDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__RemainderDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__AddDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__SubtractDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__MultiplyDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__DivideDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__ModuloDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__CompareDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Implicit_FromByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Implicit_FromChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Decimal__op_Implicit_FromInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Decimal__op_Implicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__op_Implicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__op_Implicit_FromSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // System_Decimal__op_Implicit_FromUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // System_Decimal__op_Implicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__op_Implicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__op_Explicit_ToByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_FromDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__op_Explicit_FromSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_DateTime__MinValue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Field Signature // System_DateTime__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_DateTime__CompareDateTimeDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_Collections_IEnumerable__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_IEnumerator, // System_Collections_IEnumerator__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_IEnumerator__Reset (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Collections_Generic_IEnumerable_T__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerator_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_IDisposable__Dispose (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_IDisposable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Array__Length (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__LongLength (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Array__GetLowerBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__GetUpperBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__EqualsObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__ToString (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Object__ReferenceEquals (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_IntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_IntPtr__op_Explicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_IntPtr__op_Explicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_UIntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_UIntPtr__op_Explicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_UIntPtr__op_Explicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Nullable_T_GetValueOrDefault (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_Value (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_HasValue (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Nullable_T__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Implicit_FromT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Explicit_ToT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type }; string[] allNames = new string[(int)SpecialMember.Count] { ".ctor", // System_String__CtorSZArrayChar "Concat", // System_String__ConcatStringString "Concat", // System_String__ConcatStringStringString "Concat", // System_String__ConcatStringStringStringString "Concat", // System_String__ConcatStringArray "Concat", // System_String__ConcatObject "Concat", // System_String__ConcatObjectObject "Concat", // System_String__ConcatObjectObjectObject "Concat", // System_String__ConcatObjectArray "op_Equality", // System_String__op_Equality "op_Inequality", // System_String__op_Inequality "get_Length", // System_String__Length "get_Chars", // System_String__Chars "Format", // System_String__Format "Substring", // System_String__Substring "IsNaN", // System_Double__IsNaN "IsNaN", // System_Single__IsNaN "Combine", // System_Delegate__Combine "Remove", // System_Delegate__Remove "op_Equality", // System_Delegate__op_Equality "op_Inequality", // System_Delegate__op_Inequality "Zero", // System_Decimal__Zero "MinusOne", // System_Decimal__MinusOne "One", // System_Decimal__One ".ctor", // System_Decimal__CtorInt32 ".ctor", // System_Decimal__CtorUInt32 ".ctor", // System_Decimal__CtorInt64 ".ctor", // System_Decimal__CtorUInt64 ".ctor", // System_Decimal__CtorSingle ".ctor", // System_Decimal__CtorDouble ".ctor", // System_Decimal__CtorInt32Int32Int32BooleanByte "op_Addition", // System_Decimal__op_Addition "op_Subtraction", // System_Decimal__op_Subtraction "op_Multiply", // System_Decimal__op_Multiply "op_Division", // System_Decimal__op_Division "op_Modulus", // System_Decimal__op_Modulus "op_UnaryNegation", // System_Decimal__op_UnaryNegation "op_Increment", // System_Decimal__op_Increment "op_Decrement", // System_Decimal__op_Decrement "Negate", // System_Decimal__NegateDecimal "Remainder", // System_Decimal__RemainderDecimalDecimal "Add", // System_Decimal__AddDecimalDecimal "Subtract", // System_Decimal__SubtractDecimalDecimal "Multiply", // System_Decimal__MultiplyDecimalDecimal "Divide", // System_Decimal__DivideDecimalDecimal "Remainder", // System_Decimal__ModuloDecimalDecimal "Compare", // System_Decimal__CompareDecimalDecimal "op_Equality", // System_Decimal__op_Equality "op_Inequality", // System_Decimal__op_Inequality "op_GreaterThan", // System_Decimal__op_GreaterThan "op_GreaterThanOrEqual", // System_Decimal__op_GreaterThanOrEqual "op_LessThan", // System_Decimal__op_LessThan "op_LessThanOrEqual", // System_Decimal__op_LessThanOrEqual "op_Implicit", // System_Decimal__op_Implicit_FromByte "op_Implicit", // System_Decimal__op_Implicit_FromChar "op_Implicit", // System_Decimal__op_Implicit_FromInt16 "op_Implicit", // System_Decimal__op_Implicit_FromInt32 "op_Implicit", // System_Decimal__op_Implicit_FromInt64 "op_Implicit", // System_Decimal__op_Implicit_FromSByte "op_Implicit", // System_Decimal__op_Implicit_FromUInt16 "op_Implicit", // System_Decimal__op_Implicit_FromUInt32 "op_Implicit", // System_Decimal__op_Implicit_FromUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToByte "op_Explicit", // System_Decimal__op_Explicit_ToUInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSByte "op_Explicit", // System_Decimal__op_Explicit_ToInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSingle "op_Explicit", // System_Decimal__op_Explicit_ToDouble "op_Explicit", // System_Decimal__op_Explicit_ToChar "op_Explicit", // System_Decimal__op_Explicit_ToUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToInt32 "op_Explicit", // System_Decimal__op_Explicit_ToUInt32 "op_Explicit", // System_Decimal__op_Explicit_ToInt64 "op_Explicit", // System_Decimal__op_Explicit_FromDouble "op_Explicit", // System_Decimal__op_Explicit_FromSingle "MinValue", // System_DateTime__MinValue ".ctor", // System_DateTime__CtorInt64 "Compare", // System_DateTime__CompareDateTimeDateTime "op_Equality", // System_DateTime__op_Equality "op_Inequality", // System_DateTime__op_Inequality "op_GreaterThan", // System_DateTime__op_GreaterThan "op_GreaterThanOrEqual", // System_DateTime__op_GreaterThanOrEqual "op_LessThan", // System_DateTime__op_LessThan "op_LessThanOrEqual", // System_DateTime__op_LessThanOrEqual "GetEnumerator", // System_Collections_IEnumerable__GetEnumerator "Current", // System_Collections_IEnumerator__Current "get_Current", // System_Collections_IEnumerator__get_Current "MoveNext", // System_Collections_IEnumerator__MoveNext "Reset", // System_Collections_IEnumerator__Reset "GetEnumerator", // System_Collections_Generic_IEnumerable_T__GetEnumerator "Current", // System_Collections_Generic_IEnumerator_T__Current "get_Current", // System_Collections_Generic_IEnumerator_T__get_Current "Dispose", // System_IDisposable__Dispose "Length", // System_Array__Length "LongLength", // System_Array__LongLength "GetLowerBound", // System_Array__GetLowerBound "GetUpperBound", // System_Array__GetUpperBound "GetHashCode", // System_Object__GetHashCode "Equals", // System_Object__Equals "Equals", // System_Object__EqualsObjectObject "ToString", // System_Object__ToString "ReferenceEquals", // System_Object__ReferenceEquals "op_Explicit", // System_IntPtr__op_Explicit_ToPointer "op_Explicit", // System_IntPtr__op_Explicit_ToInt32 "op_Explicit", // System_IntPtr__op_Explicit_ToInt64 "op_Explicit", // System_IntPtr__op_Explicit_FromPointer "op_Explicit", // System_IntPtr__op_Explicit_FromInt32 "op_Explicit", // System_IntPtr__op_Explicit_FromInt64 "op_Explicit", // System_UIntPtr__op_Explicit_ToPointer "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt64 "op_Explicit", // System_UIntPtr__op_Explicit_FromPointer "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt64 "GetValueOrDefault", // System_Nullable_T_GetValueOrDefault "get_Value", // System_Nullable_T_get_Value "get_HasValue", // System_Nullable_T_get_HasValue ".ctor", // System_Nullable_T__ctor "op_Implicit", // System_Nullable_T__op_Implicit_FromT "op_Explicit", // System_Nullable_T__op_Explicit_ToT "DefaultImplementationsOfInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces "UnmanagedSignatureCallingConvention", // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention "CovariantReturnsOfClasses", // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses "VirtualStaticsInInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces ".ctor", // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(SpecialMember member) { return s_descriptors[(int)member]; } } }
// 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.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class SpecialMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static SpecialMembers() { byte[] initializationBytes = new byte[] { // System_String__CtorSZArrayChar (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_String__ConcatStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Length (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Chars (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Format (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__Substring (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Double__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Double, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Single__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Single, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Delegate__Combine (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__Remove (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Decimal__Zero (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__MinusOne (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__One (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__CtorInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__CtorUInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__CtorUInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__CtorSingle (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Decimal__CtorDouble (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__CtorInt32Int32Int32BooleanByte (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Addition (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Subtraction (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Multiply (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Division (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Modulus (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_UnaryNegation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Increment (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Decrement (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__NegateDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__RemainderDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__AddDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__SubtractDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__MultiplyDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__DivideDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__ModuloDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__CompareDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Implicit_FromByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Implicit_FromChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Decimal__op_Implicit_FromInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Decimal__op_Implicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__op_Implicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__op_Implicit_FromSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // System_Decimal__op_Implicit_FromUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // System_Decimal__op_Implicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__op_Implicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__op_Explicit_ToByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_FromDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__op_Explicit_FromSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_DateTime__MinValue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Field Signature // System_DateTime__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_DateTime__CompareDateTimeDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_Collections_IEnumerable__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_IEnumerator, // System_Collections_IEnumerator__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_IEnumerator__Reset (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Collections_Generic_IEnumerable_T__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerator_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_IDisposable__Dispose (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_IDisposable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Array__Length (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__LongLength (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Array__GetLowerBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__GetUpperBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__EqualsObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__ToString (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Object__ReferenceEquals (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_IntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_IntPtr__op_Explicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_IntPtr__op_Explicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_UIntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_UIntPtr__op_Explicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_UIntPtr__op_Explicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Nullable_T_GetValueOrDefault (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_Value (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_HasValue (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Nullable_T__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Implicit_FromT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Explicit_ToT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type }; string[] allNames = new string[(int)SpecialMember.Count] { ".ctor", // System_String__CtorSZArrayChar "Concat", // System_String__ConcatStringString "Concat", // System_String__ConcatStringStringString "Concat", // System_String__ConcatStringStringStringString "Concat", // System_String__ConcatStringArray "Concat", // System_String__ConcatObject "Concat", // System_String__ConcatObjectObject "Concat", // System_String__ConcatObjectObjectObject "Concat", // System_String__ConcatObjectArray "op_Equality", // System_String__op_Equality "op_Inequality", // System_String__op_Inequality "get_Length", // System_String__Length "get_Chars", // System_String__Chars "Format", // System_String__Format "Substring", // System_String__Substring "IsNaN", // System_Double__IsNaN "IsNaN", // System_Single__IsNaN "Combine", // System_Delegate__Combine "Remove", // System_Delegate__Remove "op_Equality", // System_Delegate__op_Equality "op_Inequality", // System_Delegate__op_Inequality "Zero", // System_Decimal__Zero "MinusOne", // System_Decimal__MinusOne "One", // System_Decimal__One ".ctor", // System_Decimal__CtorInt32 ".ctor", // System_Decimal__CtorUInt32 ".ctor", // System_Decimal__CtorInt64 ".ctor", // System_Decimal__CtorUInt64 ".ctor", // System_Decimal__CtorSingle ".ctor", // System_Decimal__CtorDouble ".ctor", // System_Decimal__CtorInt32Int32Int32BooleanByte "op_Addition", // System_Decimal__op_Addition "op_Subtraction", // System_Decimal__op_Subtraction "op_Multiply", // System_Decimal__op_Multiply "op_Division", // System_Decimal__op_Division "op_Modulus", // System_Decimal__op_Modulus "op_UnaryNegation", // System_Decimal__op_UnaryNegation "op_Increment", // System_Decimal__op_Increment "op_Decrement", // System_Decimal__op_Decrement "Negate", // System_Decimal__NegateDecimal "Remainder", // System_Decimal__RemainderDecimalDecimal "Add", // System_Decimal__AddDecimalDecimal "Subtract", // System_Decimal__SubtractDecimalDecimal "Multiply", // System_Decimal__MultiplyDecimalDecimal "Divide", // System_Decimal__DivideDecimalDecimal "Remainder", // System_Decimal__ModuloDecimalDecimal "Compare", // System_Decimal__CompareDecimalDecimal "op_Equality", // System_Decimal__op_Equality "op_Inequality", // System_Decimal__op_Inequality "op_GreaterThan", // System_Decimal__op_GreaterThan "op_GreaterThanOrEqual", // System_Decimal__op_GreaterThanOrEqual "op_LessThan", // System_Decimal__op_LessThan "op_LessThanOrEqual", // System_Decimal__op_LessThanOrEqual "op_Implicit", // System_Decimal__op_Implicit_FromByte "op_Implicit", // System_Decimal__op_Implicit_FromChar "op_Implicit", // System_Decimal__op_Implicit_FromInt16 "op_Implicit", // System_Decimal__op_Implicit_FromInt32 "op_Implicit", // System_Decimal__op_Implicit_FromInt64 "op_Implicit", // System_Decimal__op_Implicit_FromSByte "op_Implicit", // System_Decimal__op_Implicit_FromUInt16 "op_Implicit", // System_Decimal__op_Implicit_FromUInt32 "op_Implicit", // System_Decimal__op_Implicit_FromUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToByte "op_Explicit", // System_Decimal__op_Explicit_ToUInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSByte "op_Explicit", // System_Decimal__op_Explicit_ToInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSingle "op_Explicit", // System_Decimal__op_Explicit_ToDouble "op_Explicit", // System_Decimal__op_Explicit_ToChar "op_Explicit", // System_Decimal__op_Explicit_ToUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToInt32 "op_Explicit", // System_Decimal__op_Explicit_ToUInt32 "op_Explicit", // System_Decimal__op_Explicit_ToInt64 "op_Explicit", // System_Decimal__op_Explicit_FromDouble "op_Explicit", // System_Decimal__op_Explicit_FromSingle "MinValue", // System_DateTime__MinValue ".ctor", // System_DateTime__CtorInt64 "Compare", // System_DateTime__CompareDateTimeDateTime "op_Equality", // System_DateTime__op_Equality "op_Inequality", // System_DateTime__op_Inequality "op_GreaterThan", // System_DateTime__op_GreaterThan "op_GreaterThanOrEqual", // System_DateTime__op_GreaterThanOrEqual "op_LessThan", // System_DateTime__op_LessThan "op_LessThanOrEqual", // System_DateTime__op_LessThanOrEqual "GetEnumerator", // System_Collections_IEnumerable__GetEnumerator "Current", // System_Collections_IEnumerator__Current "get_Current", // System_Collections_IEnumerator__get_Current "MoveNext", // System_Collections_IEnumerator__MoveNext "Reset", // System_Collections_IEnumerator__Reset "GetEnumerator", // System_Collections_Generic_IEnumerable_T__GetEnumerator "Current", // System_Collections_Generic_IEnumerator_T__Current "get_Current", // System_Collections_Generic_IEnumerator_T__get_Current "Dispose", // System_IDisposable__Dispose "Length", // System_Array__Length "LongLength", // System_Array__LongLength "GetLowerBound", // System_Array__GetLowerBound "GetUpperBound", // System_Array__GetUpperBound "GetHashCode", // System_Object__GetHashCode "Equals", // System_Object__Equals "Equals", // System_Object__EqualsObjectObject "ToString", // System_Object__ToString "ReferenceEquals", // System_Object__ReferenceEquals "op_Explicit", // System_IntPtr__op_Explicit_ToPointer "op_Explicit", // System_IntPtr__op_Explicit_ToInt32 "op_Explicit", // System_IntPtr__op_Explicit_ToInt64 "op_Explicit", // System_IntPtr__op_Explicit_FromPointer "op_Explicit", // System_IntPtr__op_Explicit_FromInt32 "op_Explicit", // System_IntPtr__op_Explicit_FromInt64 "op_Explicit", // System_UIntPtr__op_Explicit_ToPointer "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt64 "op_Explicit", // System_UIntPtr__op_Explicit_FromPointer "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt64 "GetValueOrDefault", // System_Nullable_T_GetValueOrDefault "get_Value", // System_Nullable_T_get_Value "get_HasValue", // System_Nullable_T_get_HasValue ".ctor", // System_Nullable_T__ctor "op_Implicit", // System_Nullable_T__op_Implicit_FromT "op_Explicit", // System_Nullable_T__op_Explicit_ToT "DefaultImplementationsOfInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces "UnmanagedSignatureCallingConvention", // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention "CovariantReturnsOfClasses", // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses "VirtualStaticsInInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces ".ctor", // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(SpecialMember member) { return s_descriptors[(int)member]; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeInheritsStatement.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.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeInheritsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeInheritsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeInheritsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeInheritsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeInheritsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetInheritsNode(parentNode, _namespaceName, _ordinal, out var inheritsNode)) { return false; } node = inheritsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementInheritsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
// 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.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeElement2))] public sealed class CodeInheritsStatement : AbstractCodeElement { internal static EnvDTE80.CodeElement2 Create( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) { var element = new CodeInheritsStatement(state, parent, namespaceName, ordinal); var result = (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); return result; } internal static EnvDTE80.CodeElement2 CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeInheritsStatement(state, fileCodeModel, nodeKind, name); return (EnvDTE80.CodeElement2)ComAggregate.CreateAggregatedObject(element); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly string _namespaceName; private readonly int _ordinal; private CodeInheritsStatement( CodeModelState state, AbstractCodeMember parent, string namespaceName, int ordinal) : base(state, parent.FileCodeModel) { _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _namespaceName = namespaceName; _ordinal = ordinal; } private CodeInheritsStatement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _namespaceName = name; } internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } if (!CodeModelService.TryGetInheritsNode(parentNode, _namespaceName, _ordinal, out var inheritsNode)) { return false; } node = inheritsNode; return node != null; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementInheritsStmt; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override void SetName(string value) => throw Exceptions.ThrowENotImpl(); public override void RenameSymbol(string newName) => throw Exceptions.ThrowENotImpl(); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeRefactoringProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { /// <summary> /// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for /// a derived type that delegate to a base type. For all accessible constructors in the base /// type, the user will be offered to create a constructor in the derived type with the same /// signature if they don't already have one. This way, a user can override a type and easily /// create all the forwarding constructors. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// for a type based on the fields/properties of that type. Both of those are handled by other /// services. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateDefaultConstructorsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) return; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync( document, textSpan, forRefactoring: true, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
// 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { /// <summary> /// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for /// a derived type that delegate to a base type. For all accessible constructors in the base /// type, the user will be offered to create a constructor in the derived type with the same /// signature if they don't already have one. This way, a user can override a type and easily /// create all the forwarding constructors. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// for a type based on the fields/properties of that type. Both of those are handled by other /// services. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public GenerateDefaultConstructorsCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) return; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var service = document.GetRequiredLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync( document, textSpan, forRefactoring: true, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/Completion/CommonCompletionItem.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 Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal static class CommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, Glyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null, string displayTextPrefix = null, bool isComplexTextEdit = false) { tags = tags.NullToEmpty(); if (glyph != null) { // put glyph tags first tags = GlyphTags.GetTags(glyph.Value).AddRange(tags); } if (showsWarningIcon) { tags = tags.Add(WellKnownTags.Warning); } properties ??= ImmutableDictionary<string, string>.Empty; if (!description.IsDefault && description.Length > 0) { properties = properties.Add("Description", EncodeDescription(description)); } return CompletionItem.Create( displayText: displayText, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } public static bool HasDescription(CompletionItem item) => item.Properties.ContainsKey("Description"); public static CompletionDescription GetDescription(CompletionItem item) { if (item.Properties.TryGetValue("Description", out var encodedDescription)) { return DecodeDescription(encodedDescription); } else { return CompletionDescription.Empty; } } private static readonly char[] s_descriptionSeparators = new char[] { '|' }; private static string EncodeDescription(ImmutableArray<SymbolDisplayPart> description) => EncodeDescription(description.ToTaggedText()); private static string EncodeDescription(ImmutableArray<TaggedText> description) { if (description.Length > 0) { return string.Join("|", description .SelectMany(d => new string[] { d.Tag, d.Text }) .Select(t => t.Escape('\\', s_descriptionSeparators))); } else { return null; } } private static CompletionDescription DecodeDescription(string encoded) { var parts = encoded.Split(s_descriptionSeparators).Select(t => t.Unescape('\\')).ToArray(); var builder = ImmutableArray<TaggedText>.Empty.ToBuilder(); for (var i = 0; i < parts.Length; i += 2) { builder.Add(new TaggedText(parts[i], parts[i + 1])); } return CompletionDescription.Create(builder.ToImmutable()); } } }
// 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 Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal static class CommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, Glyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null, string displayTextPrefix = null, bool isComplexTextEdit = false) { tags = tags.NullToEmpty(); if (glyph != null) { // put glyph tags first tags = GlyphTags.GetTags(glyph.Value).AddRange(tags); } if (showsWarningIcon) { tags = tags.Add(WellKnownTags.Warning); } properties ??= ImmutableDictionary<string, string>.Empty; if (!description.IsDefault && description.Length > 0) { properties = properties.Add("Description", EncodeDescription(description)); } return CompletionItem.Create( displayText: displayText, displayTextSuffix: displayTextSuffix, displayTextPrefix: displayTextPrefix, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, inlineDescription: inlineDescription, isComplexTextEdit: isComplexTextEdit); } public static bool HasDescription(CompletionItem item) => item.Properties.ContainsKey("Description"); public static CompletionDescription GetDescription(CompletionItem item) { if (item.Properties.TryGetValue("Description", out var encodedDescription)) { return DecodeDescription(encodedDescription); } else { return CompletionDescription.Empty; } } private static readonly char[] s_descriptionSeparators = new char[] { '|' }; private static string EncodeDescription(ImmutableArray<SymbolDisplayPart> description) => EncodeDescription(description.ToTaggedText()); private static string EncodeDescription(ImmutableArray<TaggedText> description) { if (description.Length > 0) { return string.Join("|", description .SelectMany(d => new string[] { d.Tag, d.Text }) .Select(t => t.Escape('\\', s_descriptionSeparators))); } else { return null; } } private static CompletionDescription DecodeDescription(string encoded) { var parts = encoded.Split(s_descriptionSeparators).Select(t => t.Unescape('\\')).ToArray(); var builder = ImmutableArray<TaggedText>.Empty.ToBuilder(); for (var i = 0; i < parts.Length; i += 2) { builder.Add(new TaggedText(parts[i], parts[i + 1])); } return CompletionDescription.Create(builder.ToImmutable()); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdTypeTests.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 CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Public Class WinMdTypeTests Inherits BasicTestBase ''' <summary> ''' Verify that value__ in enums in WinRt are marked as public. ''' By default value__ is actually private and must be changed ''' by the compiler. ''' ''' We check the enum Windows.UI.Xaml.Controls.Primitives. ''' ComponentResourceLocation ''' </summary> <Fact> Public Sub WinMdEnum() Dim source = <compilation> <file name="a.vb"> Public Class abcdef End Class </file> </compilation> Dim comp = CreateCompilationWithWinRt(source) Dim winmdlib = comp.ExternalReferences(0) Dim winmdNS = comp.GetReferencedAssemblySymbol(winmdlib) Dim wns1 = winmdNS.GlobalNamespace.GetMember(Of NamespaceSymbol)("Windows") wns1 = wns1.GetMember(Of NamespaceSymbol)("UI") wns1 = wns1.GetMember(Of NamespaceSymbol)("Xaml") wns1 = wns1.GetMember(Of NamespaceSymbol)("Controls") wns1 = wns1.GetMember(Of NamespaceSymbol)("Primitives") Dim type = wns1.GetMember(Of PENamedTypeSymbol)("ComponentResourceLocation") Dim value = type.GetMember(Of FieldSymbol)("value__") Assert.Equal(value.DeclaredAccessibility, Accessibility.Public) End Sub <Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")> Public Sub WinMdAssemblyQualifiedType() Dim source = <compilation> <file name="a.vb"><![CDATA[ <MyAttribute(GetType(C1))> Public Class C Public Shared Sub Main() End Sub End Class Public Class MyAttribute Inherits System.Attribute Sub New(type As System.Type) End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithWinRt(source).AddReferences(AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference()) CompileAndVerify(comp, symbolValidator:=Sub(m) Dim [module] = DirectCast(m, PEModuleSymbol) Dim c = DirectCast([module].GlobalNamespace.GetTypeMember("C"), PENamedTypeSymbol) Dim attributeHandle = [module].Module.MetadataReader.GetCustomAttributes(c.Handle).Single() Dim value As String = Nothing [module].Module.TryExtractStringValueFromAttribute(attributeHandle, value) Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value) End Sub) 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 CompilationCreationTestHelpers Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Public Class WinMdTypeTests Inherits BasicTestBase ''' <summary> ''' Verify that value__ in enums in WinRt are marked as public. ''' By default value__ is actually private and must be changed ''' by the compiler. ''' ''' We check the enum Windows.UI.Xaml.Controls.Primitives. ''' ComponentResourceLocation ''' </summary> <Fact> Public Sub WinMdEnum() Dim source = <compilation> <file name="a.vb"> Public Class abcdef End Class </file> </compilation> Dim comp = CreateCompilationWithWinRt(source) Dim winmdlib = comp.ExternalReferences(0) Dim winmdNS = comp.GetReferencedAssemblySymbol(winmdlib) Dim wns1 = winmdNS.GlobalNamespace.GetMember(Of NamespaceSymbol)("Windows") wns1 = wns1.GetMember(Of NamespaceSymbol)("UI") wns1 = wns1.GetMember(Of NamespaceSymbol)("Xaml") wns1 = wns1.GetMember(Of NamespaceSymbol)("Controls") wns1 = wns1.GetMember(Of NamespaceSymbol)("Primitives") Dim type = wns1.GetMember(Of PENamedTypeSymbol)("ComponentResourceLocation") Dim value = type.GetMember(Of FieldSymbol)("value__") Assert.Equal(value.DeclaredAccessibility, Accessibility.Public) End Sub <Fact, WorkItem(1169511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1169511")> Public Sub WinMdAssemblyQualifiedType() Dim source = <compilation> <file name="a.vb"><![CDATA[ <MyAttribute(GetType(C1))> Public Class C Public Shared Sub Main() End Sub End Class Public Class MyAttribute Inherits System.Attribute Sub New(type As System.Type) End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithWinRt(source).AddReferences(AssemblyMetadata.CreateFromImage(TestResources.WinRt.W1).GetReference()) CompileAndVerify(comp, symbolValidator:=Sub(m) Dim [module] = DirectCast(m, PEModuleSymbol) Dim c = DirectCast([module].GlobalNamespace.GetTypeMember("C"), PENamedTypeSymbol) Dim attributeHandle = [module].Module.MetadataReader.GetCustomAttributes(c.Handle).Single() Dim value As String = Nothing [module].Module.TryExtractStringValueFromAttribute(attributeHandle, value) Assert.Equal("C1, W, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", value) End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Portable/xlf/CSharpResources.cs.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="cs" original="../CSharpResources.resx"> <body> <trans-unit id="CallingConventionTypeIsInvalid"> <source>Cannot use '{0}' as a calling convention modifier.</source> <target state="translated">{0} se nedá použít jako modifikátor konvence volání.</target> <note /> </trans-unit> <trans-unit id="CallingConventionTypesRequireUnmanaged"> <source>Passing '{0}' is not valid unless '{1}' is 'SignatureCallingConvention.Unmanaged'.</source> <target state="translated">Pokud {1} není SignatureCallingConvention.Unmanaged, předání hodnoty {0} není platné.</target> <note /> </trans-unit> <trans-unit id="CannotCreateConstructedFromConstructed"> <source>Cannot create constructed generic type from another constructed generic type.</source> <target state="translated">Konstruovaný obecný typ nejde vytvořit z jiného konstruovaného obecného typu.</target> <note /> </trans-unit> <trans-unit id="CannotCreateConstructedFromNongeneric"> <source>Cannot create constructed generic type from non-generic type.</source> <target state="translated">Konstruovaný obecný typ nejde vytvořit z jiného než obecného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractConversionNotInvolvingContainedType"> <source>User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type</source> <target state="new">User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractEventHasAccessors"> <source>'{0}': abstract event cannot use event accessor syntax</source> <target state="translated">{0}: abstraktní událost nemůže používat syntaxi přístupového objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfMethodGroupInExpressionTree"> <source>'&amp;' on method groups cannot be used in expression trees</source> <target state="translated">&amp; pro skupiny metod se nedá použít ve stromech výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfToNonFunctionPointer"> <source>Cannot convert &amp;method group '{0}' to non-function pointer type '{1}'.</source> <target state="translated">Skupina &amp;method {0} se nedá převést na typ ukazatele, který neukazuje na funkci ({1}).</target> <note /> </trans-unit> <trans-unit id="ERR_AltInterpolatedVerbatimStringsNotAvailable"> <source>To use '@$' instead of '$@' for an interpolated verbatim string, please use language version '{0}' or greater.</source> <target state="translated">Pokud chcete pro interpolovaný doslovný řetězec použít @$ místo $@, použijte verzi jazyka {0} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOpsOnDefault"> <source>Operator '{0}' is ambiguous on operands '{1}' and '{2}'</source> <target state="translated">Operátor {0} je na operandech {1} a {2} nejednoznačný.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOpsOnUnconstrainedDefault"> <source>Operator '{0}' cannot be applied to 'default' and operand of type '{1}' because it is a type parameter that is not known to be a reference type</source> <target state="translated">Operátor {0} nejde použít pro default a operand typu {1}, protože se jedná o parametr typu, který není znám jako odkazový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AnnotationDisallowedInObjectCreation"> <source>Cannot use a nullable reference type in object creation.</source> <target state="translated">K vytvoření objektu nejde použít typ odkazu s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNameInITuplePattern"> <source>Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.</source> <target state="translated">Názvy elementů nejsou povolené při porovnávání vzorů přes System.Runtime.CompilerServices.ITuple.</target> <note /> </trans-unit> <trans-unit id="ERR_AsNullableType"> <source>It is not legal to use nullable reference type '{0}?' in an as expression; use the underlying type '{0}' instead.</source> <target state="translated">Ve výrazu as se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignmentInitOnly"> <source>Init-only property or indexer '{0}' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.</source> <target state="translated">Vlastnost jenom pro inicializaci nebo indexer {0} se dá přiřadit jenom k inicializátoru objektu, pomocí klíčového slova this nebo base v konstruktoru instance nebo k přístupovému objektu init.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrDependentTypeNotAllowed"> <source>Type '{0}' cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type '{0}' cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrTypeArgCannotBeTypeVar"> <source>'{0}': an attribute type argument cannot use type parameters</source> <target state="new">'{0}': an attribute type argument cannot use type parameters</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeNotOnEventAccessor"> <source>Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro přístupové objekty události. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributesRequireParenthesizedLambdaExpression"> <source>Attributes on lambda expressions require a parenthesized parameter list.</source> <target state="new">Attributes on lambda expressions require a parenthesized parameter list.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyWithSetterCantBeReadOnly"> <source>Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor.</source> <target state="translated">Automaticky implementovanou vlastnost {0} nelze označit modifikátorem readonly, protože má přístupový objekt set.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoSetterCantBeReadOnly"> <source>Auto-implemented 'set' accessor '{0}' cannot be marked 'readonly'.</source> <target state="translated">Automaticky implementovaný přístupový objekt set {0} nelze označit modifikátorem readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitForEachMissingMember"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance or extension definition for '{1}'</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje vhodnou veřejnou definici instance nebo rozšíření pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitForEachMissingMemberWrongAsync"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'foreach' rather than 'await foreach'?</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu foreach místo await foreach?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractBinaryOperatorSignature"> <source>One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractIncDecRetType"> <source>The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter.</source> <target state="new">The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractIncDecSignature"> <source>The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractShiftOperatorSignature"> <source>The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int</source> <target state="new">The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractStaticMemberAccess"> <source>A static abstract interface member can be accessed only on a type parameter.</source> <target state="new">A static abstract interface member can be accessed only on a type parameter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractUnaryOperatorSignature"> <source>The parameter of a unary operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">The parameter of a unary operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerArgumentExpressionParamWithoutDefaultValue"> <source>The CallerArgumentExpressionAttribute may only be applied to parameters with default values</source> <target state="new">The CallerArgumentExpressionAttribute may only be applied to parameters with default values</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicAwaitForEach"> <source>Cannot use a collection of dynamic type in an asynchronous foreach</source> <target state="translated">V asynchronním příkazu foreach nejde použít kolekce dynamického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFieldTypeInRecord"> <source>The type '{0}' may not be used for a field of a record.</source> <target state="translated">Typ {0} se nedá použít pro pole záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFuncPointerArgCount"> <source>Function pointer '{0}' does not take {1} arguments</source> <target state="translated">Ukazatel na funkci {0} nepřijímá tento počet argumentů: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadFuncPointerParamModifier"> <source>'{0}' cannot be used as a modifier on a function pointer parameter.</source> <target state="translated">{0} se nedá použít jako modifikátor v parametru ukazatele na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInheritanceFromRecord"> <source>Only records may inherit from records.</source> <target state="translated">Ze záznamů můžou dědit jenom záznamy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInitAccessor"> <source>The 'init' accessor is not valid on static members</source> <target state="translated">Přístupový objekt init není platný pro statické členy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullableContextOption"> <source>Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'</source> <target state="translated">Neplatná možnost {0} pro /nullable. Je třeba použít disable, enable, warnings nebo annotations.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullableTypeof"> <source>The typeof operator cannot be used on a nullable reference type</source> <target state="translated">Operátor typeof nejde použít na typ odkazů s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_BadOpOnNullOrDefaultOrNew"> <source>Operator '{0}' cannot be applied to operand '{1}'</source> <target state="translated">Operátor {0} nejde použít pro operand {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPatternExpression"> <source>Invalid operand for pattern match; value required, but found '{0}'.</source> <target state="translated">Neplatný operand pro porovnávací vzorek. Vyžaduje se hodnota, ale nalezeno: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordBase"> <source>Records may only inherit from object or another record</source> <target state="translated">Záznamy můžou dědit jenom z objektu nebo jiného záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordMemberForPositionalParameter"> <source>Record member '{0}' must be a readable instance property or field of type '{1}' to match positional parameter '{2}'.</source> <target state="needs-review-translation">Člen záznamu {0} musí být čitelná vlastnost instance typu {1}, která se bude shodovat s pozičním parametrem {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitchValue"> <source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source> <target state="translated">Chyba syntaxe příkazového řádku: {0} není platná hodnota možnosti {1}. Hodnota musí mít tvar {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BuilderAttributeDisallowed"> <source>The AsyncMethodBuilder attribute is disallowed on anonymous methods without an explicit return type.</source> <target state="new">The AsyncMethodBuilder attribute is disallowed on anonymous methods without an explicit return type.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotClone"> <source>The receiver type '{0}' is not a valid record type and is not a struct type.</source> <target state="new">The receiver type '{0}' is not a valid record type and is not a struct type.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotConvertAddressOfToDelegate"> <source>Cannot convert &amp;method group '{0}' to delegate type '{0}'.</source> <target state="translated">Skupina &amp;metody {0} se nedá převést na typ delegáta {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotInferDelegateType"> <source>The delegate type could not be inferred.</source> <target state="new">The delegate type could not be inferred.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotSpecifyManagedWithUnmanagedSpecifiers"> <source>'managed' calling convention cannot be combined with unmanaged calling convention specifiers.</source> <target state="translated">Konvence volání managed se nedá kombinovat se specifikátory konvence nespravovaného volání.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseFunctionPointerAsFixedLocal"> <source>The type of a local declared in a fixed statement cannot be a function pointer type.</source> <target state="translated">Lokální proměnná deklarovaná v příkazu fixed nemůže být typu ukazatel na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseManagedTypeInUnmanagedCallersOnly"> <source>Cannot use '{0}' as a {1} type on a method attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">V metodě, která má atribut UnmanagedCallersOnly, se nedá jako typ {1} použít {0}.</target> <note>1 is the localized word for 'parameter' or 'return'. UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_CannotUseReducedExtensionMethodInAddressOf"> <source>Cannot use an extension method with a receiver as the target of a '&amp;' operator.</source> <target state="translated">Rozšiřující metoda, kde jako cíl je nastavený příjemce, se nedá použít jako cíl operátoru &amp;.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseSelfAsInterpolatedStringHandlerArgument"> <source>InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.</source> <target state="new">InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.</target> <note>InterpolatedStringHandlerArgumentAttribute is a type name and should not be translated.</note> </trans-unit> <trans-unit id="ERR_CantChangeInitOnlyOnOverride"> <source>'{0}' must match by init-only of overridden member '{1}'</source> <target state="translated">{0} musí odpovídat vlastnosti jenom pro inicializaci přepsaného člena {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethReturnType"> <source>Cannot convert {0} to type '{1}' because the return type does not match the delegate return type</source> <target state="new">Cannot convert {0} to type '{1}' because the return type does not match the delegate return type</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseInOrOutInArglist"> <source>__arglist cannot have an argument passed by 'in' or 'out'</source> <target state="translated">__arglist nemůže mít argument předávaný pomocí in nebo out</target> <note /> </trans-unit> <trans-unit id="ERR_CloneDisallowedInRecord"> <source>Members named 'Clone' are disallowed in records.</source> <target state="translated">Členy s názvem Clone se v záznamech nepovolují.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberNotStatic"> <source>'{0}' does not implement static interface member '{1}'. '{2}' cannot implement the interface member because it is not static.</source> <target state="new">'{0}' does not implement static interface member '{1}'. '{2}' cannot implement the interface member because it is not static.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongInitOnly"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}'.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConWithUnmanagedCon"> <source>Type parameter '{1}' has the 'unmanaged' constraint so '{1}' cannot be used as a constraint for '{0}'</source> <target state="translated">Parametr typu {1} má omezení unmanaged, takže není možné používat {1} jako omezení pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnLocalFunction"> <source>Local function '{0}' must be 'static' in order to use the Conditional attribute</source> <target state="translated">Aby bylo možné používat atribut Conditional, musí být místní funkce {0} static.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantPatternVsOpenType"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}'. Please use language version '{2}' or greater to match an open type with a constant pattern.</source> <target state="translated">Výraz typu {0} nelze zpracovat vzorem typu {1}. Použijte prosím verzi jazyka {2} nebo vyšší, aby odpovídala otevřenému typu se vzorem konstanty.</target> <note /> </trans-unit> <trans-unit id="ERR_CopyConstructorMustInvokeBaseCopyConstructor"> <source>A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.</source> <target state="translated">Kopírovací konstruktor v záznamu musí volat kopírovací konstruktor základní třídy, případně konstruktor objektu bez parametrů, pokud záznam dědí z objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_CopyConstructorWrongAccessibility"> <source>A copy constructor '{0}' must be public or protected because the record is not sealed.</source> <target state="translated">Kopírovací konstruktor {0} musí být veřejný nebo chráněný, protože záznam není zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructParameterNameMismatch"> <source>The name '{0}' does not match the corresponding 'Deconstruct' parameter '{1}'.</source> <target state="translated">Název {0} neodpovídá příslušnému parametru Deconstruct {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultConstraintOverrideOnly"> <source>The 'default' constraint is valid on override and explicit interface implementation methods only.</source> <target state="translated">Omezení default je platné jen v přepsaných metodách a metodách explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má neabstraktní člen. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultLiteralNoTargetType"> <source>There is no target type for the default literal.</source> <target state="translated">Není k dispozici žádný cílový typ pro výchozí literál.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPattern"> <source>A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.</source> <target state="translated">Výchozí literál default není platný jako vzor. Podle potřeby použijte jiný literál (například 0 nebo null). Pokud chcete, aby odpovídalo vše, použijte vzor discard „_“.</target> <note /> </trans-unit> <trans-unit id="ERR_DesignatorBeneathPatternCombinator"> <source>A variable may not be declared within a 'not' or 'or' pattern.</source> <target state="translated">Proměnná se nedá deklarovat ve vzoru not nebo or.</target> <note /> </trans-unit> <trans-unit id="ERR_DiscardPatternInSwitchStatement"> <source>The discard pattern is not permitted as a case label in a switch statement. Use 'case var _:' for a discard pattern, or 'case @_:' for a constant named '_'.</source> <target state="translated">Tento vzor discard není povolený jako návěstí příkazu case v příkazu switch. Použijte „case var _:“ pro vzor discard nebo „case @_:“ pro konstantu s názvem „_“.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideBaseEqualityContract"> <source>'{0}' does not override expected property from '{1}'.</source> <target state="translated">{0} nepřepisuje očekávanou vlastnost z {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideBaseMethod"> <source>'{0}' does not override expected method from '{1}'.</source> <target state="translated">{0} nepřepisuje očekávanou metodu z {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideMethodFromObject"> <source>'{0}' does not override expected method from 'object'.</source> <target state="translated">{0} nepřepisuje očekávanou metodu z object.</target> <note /> </trans-unit> <trans-unit id="ERR_DupReturnTypeMod"> <source>A return type can only have one '{0}' modifier.</source> <target state="translated">Návratový typ může mít jen jeden modifikátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateExplicitImpl"> <source>'{0}' is explicitly implemented more than once.</source> <target state="translated">Položka {0} je explicitně implementována více než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceWithDifferencesInBaseList"> <source>'{0}' is already listed in the interface list on type '{2}' as '{1}'.</source> <target state="translated">{0} je již uvedeno v seznamu rozhraní u typu {2} jako {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNullSuppression"> <source>Duplicate null suppression operator ('!')</source> <target state="translated">Duplicitní operátor potlačení hodnoty null (!)</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyReadOnlyMods"> <source>Cannot specify 'readonly' modifiers on both accessors of property or indexer '{0}'. Instead, put a 'readonly' modifier on the property itself.</source> <target state="translated">Pro přístupové objekty vlastnosti i indexeru {0} nelze zadat modifikátory readonly. Místo toho zadejte modifikátor readonly jenom pro vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_ElseCannotStartStatement"> <source>'else' cannot start a statement.</source> <target state="translated">Příkaz nemůže začínat na else.</target> <note /> </trans-unit> <trans-unit id="ERR_EntryPointCannotBeUnmanagedCallersOnly"> <source>Application entry points cannot be attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">Vstupní body aplikací nemůžou mít atribut UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_EqualityContractRequiresGetter"> <source>Record equality contract property '{0}' must have a get accessor.</source> <target state="translated">Vlastnost kontraktu rovnosti záznamu {0} musí mít přístupový objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplementationOfOperatorsMustBeStatic"> <source>Explicit implementation of a user-defined operator '{0}' must be declared static</source> <target state="new">Explicit implementation of a user-defined operator '{0}' must be declared static</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitNullableAttribute"> <source>Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.</source> <target state="translated">Explicitní použití System.Runtime.CompilerServices.NullableAttribute není povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyMismatchInitOnly"> <source>Accessors '{0}' and '{1}' should both be init-only or neither</source> <target state="translated">Přístupové objekty {0} a {1} by měly být buď oba jenom pro inicializaci, nebo ani jeden.</target> <note /> </trans-unit> <trans-unit id="ERR_ExprCannotBeFixed"> <source>The given expression cannot be used in a fixed statement</source> <target state="translated">Daný výraz nelze použít v příkazu fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeCantContainNullCoalescingAssignment"> <source>An expression tree may not contain a null coalescing assignment</source> <target state="translated">Strom výrazu nesmí obsahovat přiřazení představující sloučení s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeCantContainRefStruct"> <source>Expression tree cannot contain value of ref struct or restricted type '{0}'.</source> <target state="translated">Strom výrazu nemůže obsahovat hodnotu struktury REF ani zakázaný typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAbstractStaticMemberAccess"> <source>An expression tree may not contain an access of static abstract interface member</source> <target state="new">An expression tree may not contain an access of static abstract interface member</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsFromEndIndexExpression"> <source>An expression tree may not contain a from-end index ('^') expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz indexu od-do (^).</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion"> <source>An expression tree may not contain an interpolated string handler conversion.</source> <target state="new">An expression tree may not contain an interpolated string handler conversion.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer"> <source>An expression tree may not contain a pattern System.Index or System.Range indexer access</source> <target state="translated">Strom výrazů možná neobsahuje vzor přístupu indexeru System.Index nebo System.Range.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsRangeExpression"> <source>An expression tree may not contain a range ('..') expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz rozsahu (..).</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsSwitchExpression"> <source>An expression tree may not contain a switch expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz switch.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleBinOp"> <source>An expression tree may not contain a tuple == or != operator</source> <target state="translated">Strom výrazů nesmí obsahovat operátor řazené kolekce členů == nebo !=.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsWithExpression"> <source>An expression tree may not contain a with-expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz with.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternEventInitializer"> <source>'{0}': extern event cannot have initializer</source> <target state="translated">{0}: Externí událost nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureInPreview"> <source>The feature '{0}' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.</source> <target state="translated">Funkce {0} je aktuálně ve verzi Preview a je *nepodporovaná*. Pokud chcete používat funkce Preview, použijte jazykovou verzi preview.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureIsExperimental"> <source>Feature '{0}' is experimental and unsupported; use '/features:{1}' to enable.</source> <target state="translated">Funkce {0} je zkušební, a proto není podporovaná. K aktivaci použijte /features:{1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion10"> <source>Feature '{0}' is not available in C# 10.0. Please use language version {1} or greater.</source> <target state="new">Feature '{0}' is not available in C# 10.0. Please use language version {1} or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion8"> <source>Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion8_0"> <source>Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion9"> <source>Feature '{0}' is not available in C# 9.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 9.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldLikeEventCantBeReadOnly"> <source>Field-like event '{0}' cannot be 'readonly'.</source> <target state="translated">Událost podobná poli {0} nemůže mít modifikátor readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_FileScopedAndNormalNamespace"> <source>Source file can not contain both file-scoped and normal namespace declarations.</source> <target state="new">Source file can not contain both file-scoped and normal namespace declarations.</target> <note /> </trans-unit> <trans-unit id="ERR_FileScopedNamespaceNotBeforeAllMembers"> <source>File-scoped namespace must precede all other members in a file.</source> <target state="new">File-scoped namespace must precede all other members in a file.</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachMissingMemberWrongAsync"> <source>foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'await foreach' rather than 'foreach'?</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu await foreach místo foreach?</target> <note /> </trans-unit> <trans-unit id="ERR_FuncPtrMethMustBeStatic"> <source>Cannot create a function pointer for '{0}' because it is not a static method</source> <target state="translated">Pro {0} se nedá vytvořit ukazatel na funkci, protože to není statická metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_FuncPtrRefMismatch"> <source>Ref mismatch between '{0}' and function pointer '{1}'</source> <target state="translated">Mezi {0} a ukazatelem na funkci {1} se neshoduje odkaz.</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionPointerTypesInAttributeNotSupported"> <source>Using a function pointer type in a 'typeof' in an attribute is not supported.</source> <target state="needs-review-translation">V typeof v atributu se nepodporuje používání typu ukazatele funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionPointersCannotBeCalledWithNamedArguments"> <source>A function pointer cannot be called with named arguments.</source> <target state="translated">Ukazatel na funkci se nedá zavolat s pojmenovanými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers"> <source>The interface '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The constraint interface '{1}' or its base interface has static abstract members.</source> <target state="new">The interface '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The constraint interface '{1}' or its base interface has static abstract members.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalUsingInNamespace"> <source>A global using directive cannot be used in a namespace declaration.</source> <target state="new">A global using directive cannot be used in a namespace declaration.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalUsingOutOfOrder"> <source>A global using directive must precede all non-global using directives.</source> <target state="new">A global using directive must precede all non-global using directives.</target> <note /> </trans-unit> <trans-unit id="ERR_GoToBackwardJumpOverUsingVar"> <source>A goto cannot jump to a location before a using declaration within the same block.</source> <target state="translated">Příkaz goto nemůže přejít na místo před deklarací using ve stejném bloku.</target> <note /> </trans-unit> <trans-unit id="ERR_GoToForwardJumpOverUsingVar"> <source>A goto cannot jump to a location after a using declaration.</source> <target state="translated">Příkaz goto nemůže přejít na místo za deklarací using.</target> <note /> </trans-unit> <trans-unit id="ERR_HiddenPositionalMember"> <source>The positional member '{0}' found corresponding to this parameter is hidden.</source> <target state="translated">Poziční člen {0}, který odpovídá tomuto parametru je skrytý.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalSuppression"> <source>The suppression operator is not allowed in this context</source> <target state="translated">Operátor potlačení není v tomto kontextu povolený.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitIndexIndexerWithName"> <source>Invocation of implicit Index Indexer cannot name the argument.</source> <target state="translated">Volání implicitního indexeru indexů nemůže pojmenovat argument.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationIllegalTargetType"> <source>The type '{0}' may not be used as the target type of new()</source> <target state="translated">Typ {0} se nedá použít jako cílový typ příkazu new().</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationNoTargetType"> <source>There is no target type for '{0}'</source> <target state="translated">Není k dispozici žádný cílový typ pro {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationNotValid"> <source>Use of new() is not valid in this context</source> <target state="translated">Použití new() není v tomto kontextu platné</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitRangeIndexerWithName"> <source>Invocation of implicit Range Indexer cannot name the argument.</source> <target state="translated">Volání implicitního indexeru rozsahů nemůže pojmenovat argument.</target> <note /> </trans-unit> <trans-unit id="ERR_InDynamicMethodArg"> <source>Arguments with 'in' modifier cannot be used in dynamically dispatched expressions.</source> <target state="translated">Argumenty s modifikátorem in se nedají použít v dynamicky volaných výrazech.</target> <note /> </trans-unit> <trans-unit id="ERR_InheritingFromRecordWithSealedToString"> <source>Inheriting from a record with a sealed 'Object.ToString' is not supported in C# {0}. Please use language version '{1}' or greater.</source> <target state="translated">Dědění ze záznamu se zapečetěným objektem Object.ToString se v jazyce C# {0} nepodporuje. Použijte prosím jazykovou verzi {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_InitCannotBeReadonly"> <source>'init' accessors cannot be marked 'readonly'. Mark '{0}' readonly instead.</source> <target state="translated">Přístupové objekty init se nedají označit jako jen pro čtení. Místo toho označte jako jen pro čtení {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InstancePropertyInitializerInInterface"> <source>Instance properties in interfaces cannot have initializers.</source> <target state="translated">Vlastnosti instance v rozhraních nemůžou mít inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod"> <source>'UnmanagedCallersOnly' method '{0}' cannot implement interface member '{1}' in type '{2}'</source> <target state="new">'UnmanagedCallersOnly' method '{0}' cannot implement interface member '{1}' in type '{2}'</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_InterfaceImplementedImplicitlyByVariadic"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because it has an __arglist parameter</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože má parametr __arglist.</target> <note /> </trans-unit> <trans-unit id="ERR_InternalError"> <source>Internal error in the C# compiler.</source> <target state="translated">Vnitřní chyba v kompilátoru jazyka C#</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentAttributeMalformed"> <source>The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.</source> <target state="new">The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.</target> <note>InterpolatedStringHandlerArgumentAttribute is a type name and should not be translated.</note> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString"> <source>Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.</source> <target state="new">Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified"> <source>Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.</source> <target state="new">Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerCreationCannotUseDynamic"> <source>An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.</source> <target state="new">An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerMethodReturnInconsistent"> <source>Interpolated string handler method '{0}' has inconsistent return type. Expected to return '{1}'.</source> <target state="new">Interpolated string handler method '{0}' has inconsistent return type. Expected to return '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerMethodReturnMalformed"> <source>Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.</source> <target state="new">Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.</target> <note>void and bool are keywords</note> </trans-unit> <trans-unit id="ERR_InvalidFuncPointerReturnTypeModifier"> <source>'{0}' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'.</source> <target state="translated">{0} není platný modifikátor návratového typu ukazatele na funkci. Platné modifikátory jsou ref a ref readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFunctionPointerCallingConvention"> <source>'{0}' is not a valid calling convention specifier for a function pointer.</source> <target state="translated">{0} není platný specifikátor konvence volání pro ukazatel na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHashAlgorithmName"> <source>Invalid hash algorithm name: '{0}'</source> <target state="translated">Neplatný název algoritmu hash: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInterpolatedStringHandlerArgumentName"> <source>'{0}' is not a valid parameter name from '{1}'.</source> <target state="new">'{0}' is not a valid parameter name from '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidModifierForLanguageVersion"> <source>The modifier '{0}' is not valid for this item in C# {1}. Please use language version '{2}' or greater.</source> <target state="translated">Modifikátor {0} není platný pro tuto položku v jazyce C# {1}. Použijte prosím verzi jazyka {2} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNameInSubpattern"> <source>Identifier or a simple member access expected.</source> <target state="new">Identifier or a simple member access expected.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidObjectCreation"> <source>Invalid object creation</source> <target state="translated">Vytvoření neplatného objektu</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPropertyReadOnlyMods"> <source>Cannot specify 'readonly' modifiers on both property or indexer '{0}' and its accessor. Remove one of them.</source> <target state="translated">Pro vlastnost nebo indexer {0} i jejich přístupový objekt nelze zadat modifikátory readonly. Odeberte jeden z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidStackAllocArray"> <source>"Invalid rank specifier: expected ']'</source> <target state="translated">Specifikátor rozsahu je neplatný. Očekávala se pravá hranatá závorka ].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUnmanagedCallersOnlyCallConv"> <source>'{0}' is not a valid calling convention type for 'UnmanagedCallersOnly'.</source> <target state="translated">{0} není platný typ konvence volání pro UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_InvalidWithReceiverType"> <source>The receiver of a `with` expression must have a non-void type.</source> <target state="translated">Příjemce výrazu with musí mít neprázdný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_IsNullableType"> <source>It is not legal to use nullable reference type '{0}?' in an is-type expression; use the underlying type '{0}' instead.</source> <target state="translated">Ve výrazu is-type se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_IsPatternImpossible"> <source>An expression of type '{0}' can never match the provided pattern.</source> <target state="translated">Výraz typu {0} nesmí nikdy odpovídat poskytnutému vzoru.</target> <note /> </trans-unit> <trans-unit id="ERR_IteratorMustBeAsync"> <source>Method '{0}' with an iterator block must be 'async' to return '{1}'</source> <target state="translated">Metoda {0} s blokem iterátoru musí být asynchronní, aby vrátila {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaWithAttributesToExpressionTree"> <source>A lambda expression with attributes cannot be converted to an expression tree</source> <target state="new">A lambda expression with attributes cannot be converted to an expression tree</target> <note /> </trans-unit> <trans-unit id="ERR_LineSpanDirectiveEndLessThanStart"> <source>The #line directive end position must be greater than or equal to the start position</source> <target state="new">The #line directive end position must be greater than or equal to the start position</target> <note /> </trans-unit> <trans-unit id="ERR_LineSpanDirectiveInvalidValue"> <source>The #line directive value is missing or out of range</source> <target state="new">The #line directive value is missing or out of range</target> <note /> </trans-unit> <trans-unit id="ERR_MethFuncPtrMismatch"> <source>No overload for '{0}' matches function pointer '{1}'</source> <target state="translated">Žádná přetížená metoda {0} neodpovídá ukazateli na funkci {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingAddressOf"> <source>Cannot convert method group to function pointer (Are you missing a '&amp;'?)</source> <target state="translated">Skupina metod se nedá převést na ukazatel na funkci (nechybí &amp;)?</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPattern"> <source>Pattern missing</source> <target state="translated">Chybějící vzor</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerCannotBeUnmanagedCallersOnly"> <source>Module initializer cannot be attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">Inicializátor modulu nemůže mít atribut UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric"> <source>Module initializer method '{0}' must not be generic and must not be contained in a generic type</source> <target state="translated">Inicializační metoda modulu {0} nemůže být obecná a nesmí obsahovat obecný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType"> <source>Module initializer method '{0}' must be accessible at the module level</source> <target state="translated">Inicializační metoda modulu {0} musí být přístupná na úrovni modulu.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeOrdinary"> <source>A module initializer must be an ordinary member method</source> <target state="translated">Inicializátor modulu musí být běžná členská metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid"> <source>Module initializer method '{0}' must be static, must have no parameters, and must return 'void'</source> <target state="translated">Inicializační metoda modulu {0} musí být statická, nesmí mít žádné parametry a musí vracet void.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir"> <source>Multiple analyzer config files cannot be in the same directory ('{0}').</source> <target state="translated">Ve stejném adresáři nemůže být více konfiguračních souborů analyzátoru ({0}).</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEnumeratorCancellationAttributes"> <source>The attribute [EnumeratorCancellation] cannot be used on multiple parameters</source> <target state="translated">Atribut [EnumeratorCancellation] nejde použít na víc parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleFileScopedNamespace"> <source>Source file can only contain one file-scoped namespace declaration.</source> <target state="new">Source file can only contain one file-scoped namespace declaration.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleRecordParameterLists"> <source>Only a single record partial declaration may have a parameter list</source> <target state="translated">Seznam parametrů může mít jenom částečná deklarace jednoho záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundWithUnmanaged"> <source>The 'new()' constraint cannot be used with the 'unmanaged' constraint</source> <target state="translated">Omezení new() nejde používat s omezením unmanaged.</target> <note /> </trans-unit> <trans-unit id="ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString"> <source>Newlines are not allowed inside a non-verbatim interpolated string</source> <target state="new">Newlines are not allowed inside a non-verbatim interpolated string</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIAsyncDispWrongAsync"> <source>'{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. Did you mean 'using' rather than 'await using'?</source> <target state="translated">{0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync. Měli jste v úmyslu použít using nebo await using?</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIDispWrongAsync"> <source>'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'?</source> <target state="translated">{0}: Typ použitý v příkazu using musí být implicitně převoditelný na System.IDisposable. Neměli jste v úmyslu použít await using místo using?</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerArgumentExpressionParam"> <source>CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="new">CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</target> <note /> </trans-unit> <trans-unit id="ERR_NoCopyConstructorInBaseType"> <source>No accessible copy constructor found in base type '{0}'.</source> <target state="translated">V základním typu {0} se nenašel žádný přístupný kopírovací konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConvTargetTypedConditional"> <source>Conditional expression is not valid in language version {0} because a common type was not found between '{1}' and '{2}'. To use a target-typed conversion, upgrade to language version {3} or greater.</source> <target state="new">Conditional expression is not valid in language version {0} because a common type was not found between '{1}' and '{2}'. To use a target-typed conversion, upgrade to language version {3} or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_NoOutputDirectory"> <source>Output directory could not be determined</source> <target state="translated">Nepovedlo se určit výstupní adresář.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPrivateAPIInRecord"> <source>Record member '{0}' must be private.</source> <target state="translated">Člen záznamu {0} musí být privátní.</target> <note /> </trans-unit> <trans-unit id="ERR_NonProtectedAPIInRecord"> <source>Record member '{0}' must be protected.</source> <target state="translated">Člen záznamu {0} musí být chráněný.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPublicAPIInRecord"> <source>Record member '{0}' must be public.</source> <target state="translated">Člen záznamu {0} musí být veřejný.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPublicParameterlessStructConstructor"> <source>The parameterless struct constructor must be 'public'.</source> <target state="new">The parameterless struct constructor must be 'public'.</target> <note /> </trans-unit> <trans-unit id="ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName"> <source>'{0}' is not an instance method, the receiver cannot be an interpolated string handler argument.</source> <target state="new">'{0}' is not an instance method, the receiver cannot be an interpolated string handler argument.</target> <note /> </trans-unit> <trans-unit id="ERR_NotOverridableAPIInRecord"> <source>'{0}' must allow overriding because the containing record is not sealed.</source> <target state="translated">{0} musí povolovat přepisování, protože obsahující záznam není zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_NullInvalidInterpolatedStringHandlerArgumentName"> <source>null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.</source> <target state="new">null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDirectiveQualifierExpected"> <source>Expected 'enable', 'disable', or 'restore'</source> <target state="translated">Očekávala se hodnota enable, disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDirectiveTargetExpected"> <source>Expected 'warnings', 'annotations', or end of directive</source> <target state="translated">Očekávala se možnost warnings nebo annotations nebo konec direktivy.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableOptionNotAvailable"> <source>Invalid '{0}' value: '{1}' for C# {2}. Please use language version '{3}' or greater.</source> <target state="translated">Neplatná hodnota {0}: {1} pro jazyk C# {2}. Použijte prosím verzi jazyka {3} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableUnconstrainedTypeParameter"> <source>A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '{0}' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint.</source> <target state="translated">Pokud se nepoužívá verze jazyka {0} nebo novější, musí být pro parametr typu s možnou hodnotou null známo, že má typ hodnoty nebo typ odkazu, který není možné nastavit na null. Zvažte možnost změnit verzi jazyka nebo přidat class, struct nebo omezení typu.</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedTypeArgument"> <source>Omitting the type argument is not allowed in the current context</source> <target state="translated">V aktuálním kontextu se vynechání argumentu typu nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_OutVariableCannotBeByRef"> <source>An out variable cannot be declared as a ref local</source> <target state="translated">Výstupní proměnná nemůže být deklarovaná jako lokální proměnná podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideDefaultConstraintNotSatisfied"> <source>Method '{0}' specifies a 'default' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is constrained to a reference type or a value type.</source> <target state="translated">Metoda {0} určuje omezení default pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není omezený na typ odkazu nebo hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideRefConstraintNotSatisfied"> <source>Method '{0}' specifies a 'class' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a reference type.</source> <target state="translated">Metoda {0} určuje omezení class pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není odkazový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideValConstraintNotSatisfied"> <source>Method '{0}' specifies a 'struct' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a non-nullable value type.</source> <target state="translated">Metoda {0} určuje omezení struct pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodAccessibilityDifference"> <source>Both partial method declarations must have identical accessibility modifiers.</source> <target state="translated">Obě deklarace částečných metod musí mít shodné modifikátory přístupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodExtendedModDifference"> <source>Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers.</source> <target state="translated">Obě deklarace částečných metod musí mít shodné kombinace modifikátorů virtual, override, sealed a new.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodReadOnlyDifference"> <source>Both partial method declarations must be readonly or neither may be readonly</source> <target state="translated">Obě deklarace částečné metody musí mít modifikátor readonly, nebo nesmí mít modifikátor readonly žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodRefReturnDifference"> <source>Partial method declarations must have matching ref return values.</source> <target state="translated">Deklarace částečných metod musí mít odpovídající referenční návratové hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodReturnTypeDifference"> <source>Both partial method declarations must have the same return type.</source> <target state="translated">Obě deklarace částečných metod musí mít stejný návratový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithAccessibilityModsMustHaveImplementation"> <source>Partial method '{0}' must have an implementation part because it has accessibility modifiers.</source> <target state="translated">Částečná metoda {0} musí mít implementační část, protože má modifikátory přístupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithExtendedModMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má modifikátor virtual, override, sealed, new nebo extern.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has a non-void return type.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má návratový typ jiný než void.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithOutParamMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has 'out' parameters.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má parametry out.</target> <note /> </trans-unit> <trans-unit id="ERR_PointerTypeInPatternMatching"> <source>Pattern-matching is not permitted for pointer types.</source> <target state="translated">Porovnávání vzorů není povolené pro typy ukazatelů.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleAsyncIteratorWithoutYield"> <source>The body of an async-iterator method must contain a 'yield' statement.</source> <target state="translated">Tělo metody async-iterator musí obsahovat příkaz yield.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleAsyncIteratorWithoutYieldOrAwait"> <source>The body of an async-iterator method must contain a 'yield' statement. Consider removing 'async' from the method declaration or adding a 'yield' statement.</source> <target state="translated">Tělo metody async-iterator musí obsahovat příkaz yield. Zvažte odebrání položky async z deklarace metody nebo přidání příkazu yield.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyPatternNameMissing"> <source>A property subpattern requires a reference to the property or field to be matched, e.g. '{{ Name: {0} }}'</source> <target state="translated">Dílčí vzor vlastnosti vyžaduje odkaz na vlastnost nebo pole k přiřazení, např. „{{ Name: {0} }}“.</target> <note /> </trans-unit> <trans-unit id="ERR_ReAbstractionInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má reabstrakci člena ze základního rozhraní. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyModMissingAccessor"> <source>'{0}': 'readonly' can only be used on accessors if the property or indexer has both a get and a set accessor</source> <target state="translated">{0}: U přístupových objektů se modifikátor readonly může použít jenom v případě, že vlastnost nebo indexer má přístupový objekt get i set.</target> <note /> </trans-unit> <trans-unit id="ERR_RecordAmbigCtor"> <source>The primary constructor conflicts with the synthesized copy constructor.</source> <target state="translated">Primární konstruktor je v konfliktu se syntetizovaně zkopírovaným konstruktorem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefAssignNarrower"> <source>Cannot ref-assign '{1}' to '{0}' because '{1}' has a narrower escape scope than '{0}'.</source> <target state="translated">Přiřazení odkazu {1} k {0} nelze provést, protože {1} má užší řídicí obor než {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefLocalOrParamExpected"> <source>The left-hand side of a ref assignment must be a ref local or parameter.</source> <target state="translated">Levá strana přiřazení odkazu musí být lokální proměnná nebo parametr odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RelationalPatternWithNaN"> <source>Relational patterns may not be used for a floating-point NaN.</source> <target state="translated">Relační vzory se nedají použít pro hodnotu Není číslo s plovoucí desetinnou čárkou.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses"> <source>'{0}': Target runtime doesn't support covariant types in overrides. Type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Cílový modul runtime nepodporuje v přepisech kovariantní typy. Typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses"> <source>'{0}': Target runtime doesn't support covariant return types in overrides. Return type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Cílový modul runtime nepodporuje v přepisech kovariantní návratové typy. Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember"> <source>Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface.</source> <target state="translated">Cílový modul runtime nepodporuje pro člena rozhraní přístupnost na úrovni Protected, Protected internal nebo Private protected.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces"> <source>Target runtime doesn't support static abstract members in interfaces.</source> <target state="new">Target runtime doesn't support static abstract members in interfaces.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support static abstract members in interfaces.</source> <target state="new">'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support static abstract members in interfaces.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv"> <source>The target runtime doesn't support extensible or runtime-environment default calling conventions.</source> <target state="translated">Cílový modul runtime nepodporuje rozšiřitelné konvence volání ani konvence volání výchozí pro prostředí modulu runtime.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedAPIInRecord"> <source>'{0}' cannot be sealed because containing record is not sealed.</source> <target state="translated">Typ {0} nemůže být zapečetěný, protože není zapečetěný obsahující záznam.</target> <note /> </trans-unit> <trans-unit id="ERR_SignatureMismatchInRecord"> <source>Record member '{0}' must return '{1}'.</source> <target state="translated">Člen záznamu {0} musí vracet {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramDisallowsMainType"> <source>Cannot specify /main if there is a compilation unit with top-level statements.</source> <target state="translated">Pokud existuje jednotka kompilace s příkazy nejvyšší úrovně, nedá se zadat /main.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramIsEmpty"> <source>At least one top-level statement must be non-empty.</source> <target state="new">At least one top-level statement must be non-empty.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement"> <source>Cannot use local variable or local function '{0}' declared in a top-level statement in this context.</source> <target state="translated">Místní proměnná nebo místní funkce {0} deklarovaná v příkazu nejvyšší úrovně v tomto kontextu se nedá použít.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramMultipleUnitsWithTopLevelStatements"> <source>Only one compilation unit can have top-level statements.</source> <target state="translated">Příkazy nejvyšší úrovně může mít jen jedna jednotka kompilace.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramNotAnExecutable"> <source>Program using top-level statements must be an executable.</source> <target state="translated">Program, který používá příkazy nejvyšší úrovně, musí být spustitelný.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleElementPositionalPatternRequiresDisambiguation"> <source>A single-element deconstruct pattern requires some other syntax for disambiguation. It is recommended to add a discard designator '_' after the close paren ')'.</source> <target state="translated">Vzor deconstruct s jedním elementem vyžaduje určitou další syntaxi pro zajištění jednoznačnosti. Doporučuje se přidat označení discard „_“ za koncovou závorku „)“.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAPIInRecord"> <source>Record member '{0}' may not be static.</source> <target state="translated">Člen záznamu {0} nemůže být statický.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAnonymousFunctionCannotCaptureThis"> <source>A static anonymous function cannot contain a reference to 'this' or 'base'.</source> <target state="translated">Statická anonymní funkce nemůže obsahovat odkaz na this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAnonymousFunctionCannotCaptureVariable"> <source>A static anonymous function cannot contain a reference to '{0}'.</source> <target state="translated">Statická anonymní funkce nemůže obsahovat odkaz na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticLocalFunctionCannotCaptureThis"> <source>A static local function cannot contain a reference to 'this' or 'base'.</source> <target state="translated">Statická lokální funkce nesmí obsahovat odkaz na this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticLocalFunctionCannotCaptureVariable"> <source>A static local function cannot contain a reference to '{0}'.</source> <target state="translated">Statická lokální funkce nesmí obsahovat odkaz na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticMemberCantBeReadOnly"> <source>Static member '{0}' cannot be marked 'readonly'.</source> <target state="translated">Statický člen {0} se nedá označit modifikátorem readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected"> <source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source> <target state="translated">Zadal se argument stdin -, ale vstup se nepřesměroval na stream standardního vstupu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchArmSubsumed"> <source>The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.</source> <target state="translated">Vzor není dostupný. Už se zpracoval v jiné části výrazu switch nebo není možné pro něj najít shodu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchCaseSubsumed"> <source>The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.</source> <target state="translated">Případ příkazu switch není dostupný. Už se zpracoval v jiném případu nebo není možné pro něj najít shodu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchExpressionNoBestType"> <source>No best type was found for the switch expression.</source> <target state="translated">Pro výraz switch se nenašel žádný optimální typ.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchGoverningExpressionRequiresParens"> <source>Parentheses are required around the switch governing expression.</source> <target state="translated">Řídící výraz switch je nutné uzavřít do závorek.</target> <note /> </trans-unit> <trans-unit id="ERR_TopLevelStatementAfterNamespaceOrType"> <source>Top-level statements must precede namespace and type declarations.</source> <target state="translated">Příkazy nejvyšší úrovně se musí nacházet před obory názvů a deklaracemi typů.</target> <note /> </trans-unit> <trans-unit id="ERR_TripleDotNotAllowed"> <source>Unexpected character sequence '...'</source> <target state="translated">Neočekáváná posloupnost znaků ...</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNameMismatch"> <source>The name '{0}' does not identify tuple element '{1}'.</source> <target state="translated">Název {0} neidentifikuje element tuple {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleSizesMismatchForBinOps"> <source>Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality {0} on the left and {1} on the right.</source> <target state="translated">Typy řazené kolekce členů, které se používají jako operandy operátoru == nebo !=, musí mít odpovídající kardinality. U tohoto operátoru je ale kardinalita typů řazené kolekce členů vlevo {0} a vpravo {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeConstraintsMustBeUniqueAndFirst"> <source>The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list.</source> <target state="translated">Omezení class, struct, unmanaged, notnull a default se nedají kombinovat ani použít více než jednou a v seznamu omezení se musí zadat jako první.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeIsNotAnInterpolatedStringHandlerType"> <source>'{0}' is not an interpolated string handler type.</source> <target state="new">'{0}' is not an interpolated string handler type.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMustBePublic"> <source>Type '{0}' must be public to be used as a calling convention.</source> <target state="translated">Aby se typ {0} dal použít jako konvence volání, musí být veřejný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly"> <source>'{0}' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.</source> <target state="translated">{0} má atribut UnmanagedCallersOnly a nedá se volat napřímo. Pro tuto metodu získejte ukazatel na funkci.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate"> <source>'{0}' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.</source> <target state="translated">{0} má atribut UnmanagedCallersOnly a nedá se převést na typ delegáta. Pro tuto metodu získejte ukazatel na funkci.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_WrongArityAsyncReturn"> <source>A generic task-like return type was expected, but the type '{0}' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic.</source> <target state="new">A generic task-like return type was expected, but the type '{0}' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic.</target> <note /> </trans-unit> <trans-unit id="HDN_DuplicateWithGlobalUsing"> <source>The using directive for '{0}' appeared previously as global using</source> <target state="new">The using directive for '{0}' appeared previously as global using</target> <note /> </trans-unit> <trans-unit id="HDN_DuplicateWithGlobalUsing_Title"> <source>The using directive appeared previously as global using</source> <target state="new">The using directive appeared previously as global using</target> <note /> </trans-unit> <trans-unit id="IDS_AsyncMethodBuilderOverride"> <source>async method builder override</source> <target state="new">async method builder override</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCovariantReturnsForOverrides"> <source>covariant returns</source> <target state="translated">kovariantní návratové hodnoty</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDiscards"> <source>discards</source> <target state="translated">discards</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtendedPropertyPatterns"> <source>extended property patterns</source> <target state="new">extended property patterns</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFileScopedNamespace"> <source>file-scoped namespace</source> <target state="new">file-scoped namespace</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGenericAttributes"> <source>generic attributes</source> <target state="new">generic attributes</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGlobalUsing"> <source>global using directive</source> <target state="new">global using directive</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitObjectCreation"> <source>target-typed object creation</source> <target state="translated">Vytvoření objektu s cílovým typem</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImprovedInterpolatedStrings"> <source>interpolated string handlers</source> <target state="new">interpolated string handlers</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInferredDelegateType"> <source>inferred delegate type</source> <target state="new">inferred delegate type</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaAttributes"> <source>lambda attributes</source> <target state="new">lambda attributes</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaReturnType"> <source>lambda return type</source> <target state="new">lambda return type</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLineSpanDirective"> <source>line span directive</source> <target state="new">line span directive</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureParameterlessStructConstructors"> <source>parameterless struct constructors</source> <target state="new">parameterless struct constructors</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePositionalFieldsInRecords"> <source>positional fields in records</source> <target state="new">positional fields in records</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecordStructs"> <source>record structs</source> <target state="new">record structs</target> <note>'record structs' is not localizable.</note> </trans-unit> <trans-unit id="IDS_FeatureSealedToStringInRecord"> <source>sealed ToString in record</source> <target state="translated">zapečetěný ToString v záznamu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStructFieldInitializers"> <source>struct field initializers</source> <target state="new">struct field initializers</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureWithOnAnonymousTypes"> <source>with on anonymous types</source> <target state="new">with on anonymous types</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticAbstractMembersInInterfaces"> <source>static abstract members in interfaces</source> <target state="new">static abstract members in interfaces</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureWithOnStructs"> <source>with on structs</source> <target state="new">with on structs</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">Sestavení {0}, které obsahuje typ {1}, se odkazuje na architekturu .NET Framework, což se nepodporuje.</target> <note>{1} is the type that was loaded, {0} is the containing assembly.</note> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework_Title"> <source>The loaded assembly references .NET Framework, which is not supported.</source> <target state="translated">Načtené sestavení se odkazuje na architekturu .NET Framework, což se nepodporuje</target> <note /> </trans-unit> <trans-unit id="WRN_AttrDependentTypeNotAllowed"> <source>Type '{0}' cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type '{0}' cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="WRN_AttrDependentTypeNotAllowed_Title"> <source>Type cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title"> <source>The CallerArgumentExpressionAttribute is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-refential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-refential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionParamForUnconsumedLocation"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionParamForUnconsumedLocation_Title"> <source>The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNamePreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNamePreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CompileTimeCheckedOverflow"> <source>The operation may overflow '{0}' at runtime (use 'unchecked' syntax to override)</source> <target state="new">The operation may overflow '{0}' at runtime (use 'unchecked' syntax to override)</target> <note /> </trans-unit> <trans-unit id="WRN_CompileTimeCheckedOverflow_Title"> <source>The operation may overflow at runtime (use 'unchecked' syntax to override)</source> <target state="new">The operation may overflow at runtime (use 'unchecked' syntax to override)</target> <note /> </trans-unit> <trans-unit id="WRN_DoNotCompareFunctionPointers"> <source>Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct.</source> <target state="translated">Porovnání ukazatelů funkcí může přinést neočekávaný výsledek, protože ukazatele na stejnou funkci můžou být rozdílné.</target> <note /> </trans-unit> <trans-unit id="WRN_DoNotCompareFunctionPointers_Title"> <source>Do not compare function pointer values</source> <target state="translated">Neporovnávat hodnoty ukazatelů funkcí</target> <note /> </trans-unit> <trans-unit id="WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters"> <source>InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</source> <target state="new">InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</target> <note /> </trans-unit> <trans-unit id="WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters_Title"> <source>InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</source> <target state="new">InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterNotNullIfNotNull"> <source>Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null.</source> <target state="translated">Parametr {0} musí mít při ukončení hodnotu jinou než null, protože parametr {1} není null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterNotNullIfNotNull_Title"> <source>Parameter must have a non-null value when exiting because parameter referenced by NotNullIfNotNull is non-null.</source> <target state="translated">Parametr musí mít při ukončení hodnotu jinou než null, protože parametr, na který se odkazuje NotNullIfNotNull není null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterOccursAfterInterpolatedStringHandlerParameter"> <source>Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.</source> <target state="new">Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterOccursAfterInterpolatedStringHandlerParameter_Title"> <source>Parameter to interpolated string handler conversion occurs after handler parameter</source> <target state="new">Parameter to interpolated string handler conversion occurs after handler parameter</target> <note /> </trans-unit> <trans-unit id="WRN_RecordEqualsWithoutGetHashCode"> <source>'{0}' defines 'Equals' but not 'GetHashCode'</source> <target state="translated">{0} definuje Equals, ale ne GetHashCode.</target> <note>'GetHashCode' and 'Equals' are not localizable.</note> </trans-unit> <trans-unit id="WRN_RecordEqualsWithoutGetHashCode_Title"> <source>Record defines 'Equals' but not 'GetHashCode'.</source> <target state="translated">Záznam definuje Equals, ale ne GetHashCode</target> <note>'GetHashCode' and 'Equals' are not localizable.</note> </trans-unit> <trans-unit id="IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction"> <source>Mixed declarations and expressions in deconstruction</source> <target state="translated">Smíšené deklarace a výrazy v dekonstrukci</target> <note /> </trans-unit> <trans-unit id="WRN_PartialMethodTypeDifference"> <source>Partial method declarations '{0}' and '{1}' have signature differences.</source> <target state="new">Partial method declarations '{0}' and '{1}' have signature differences.</target> <note /> </trans-unit> <trans-unit id="WRN_PartialMethodTypeDifference_Title"> <source>Partial method declarations have signature differences.</source> <target state="new">Partial method declarations have signature differences.</target> <note /> </trans-unit> <trans-unit id="WRN_RecordNamedDisallowed"> <source>Types and aliases should not be named 'record'.</source> <target state="translated">Typy a aliasy by neměly mít název record.</target> <note /> </trans-unit> <trans-unit id="WRN_RecordNamedDisallowed_Title"> <source>Types and aliases should not be named 'record'.</source> <target state="translated">Typy a aliasy by neměly mít název record</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnNotNullIfNotNull"> <source>Return value must be non-null because parameter '{0}' is non-null.</source> <target state="translated">Návratová hodnota musí být jiná než null, protože parametr {0} není null.</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnNotNullIfNotNull_Title"> <source>Return value must be non-null because parameter is non-null.</source> <target state="translated">Návratová hodnota musí být jiná než null, protože parametr není null</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue"> <source>The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. For example, the pattern '{0}' is not covered.</source> <target state="translated">Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu. Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue_Title"> <source>The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.</source> <target state="translated">Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu.</target> <note /> </trans-unit> <trans-unit id="WRN_SyncAndAsyncEntryPoints"> <source>Method '{0}' will not be used as an entry point because a synchronous entry point '{1}' was found.</source> <target state="translated">Metoda {0} se nepoužije jako vstupní bod, protože se našel synchronní vstupní bod {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeNotFound"> <source>Type '{0}' is not defined.</source> <target state="translated">Typ {0} není definovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedArgumentList"> <source>Unexpected argument list.</source> <target state="translated">Neočekávaný seznam argumentů</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedOrMissingConstructorInitializerInRecord"> <source>A constructor declared in a record with parameter list must have 'this' constructor initializer.</source> <target state="translated">Konstruktor deklarovaný v záznamu se seznamem parametrů musí mít inicializátor konstruktoru this.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedVarianceStaticMember"> <source>Invalid variance: The type parameter '{1}' must be {3} valid on '{0}' unless language version '{4}' or greater is used. '{1}' is {2}.</source> <target state="translated">Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}, pokud není použita verze jazyka {4} nebo vyšší. {1} je {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedBoundWithClass"> <source>'{0}': cannot specify both a constraint class and the 'unmanaged' constraint</source> <target state="translated">{0}: Nejde zadat třídu omezení a zároveň omezení unmanaged.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric"> <source>Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.</source> <target state="translated">Metody, které mají atribut UnmanagedCallersOnly, nemůžou mít obecné typy parametrů a nedají se deklarovat v obecném typu.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyRequiresStatic"> <source>'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.</source> <target state="needs-review-translation">UnmanagedCallersOnly se dá použít jen pro běžné statické metody nebo statické místní funkce.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedConstraintNotSatisfied"> <source>The type '{2}' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ, který nemůže mít hodnotu null, ani nesmí v žádné úrovni vnoření obsahovat pole, které by ji povolovalo, aby se dal použít jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedCallingConvention"> <source>The calling convention of '{0}' is not supported by the language.</source> <target state="translated">Jazyk nepodporuje konvenci volání {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedTypeForRelationalPattern"> <source>Relational patterns may not be used for a value of type '{0}'.</source> <target state="translated">Relační vzory se nedají používat pro hodnotu typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UsingVarInSwitchCase"> <source>A using variable cannot be used directly within a switch section (consider using braces). </source> <target state="translated">Proměnnou using není možné v sekci switch použít přímo (zvažte použití složených závorek). </target> <note /> </trans-unit> <trans-unit id="ERR_VarMayNotBindToType"> <source>The syntax 'var' for a pattern is not permitted to refer to a type, but '{0}' is in scope here.</source> <target state="translated">U syntaxe var pro vzor se nepovoluje odkazování na typ, ale {0} je tady v rámci rozsahu.</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInterfaceNesting"> <source>Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter.</source> <target state="translated">Výčty, třídy a struktury není možné deklarovat v rozhraní, které má parametr typu in/out.</target> <note /> </trans-unit> <trans-unit id="ERR_WrongFuncPtrCallingConvention"> <source>Calling convention of '{0}' is not compatible with '{1}'.</source> <target state="translated">Konvence volání pro {0} není kompatibilní s {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_WrongNumberOfSubpatterns"> <source>Matching the tuple type '{0}' requires '{1}' subpatterns, but '{2}' subpatterns are present.</source> <target state="translated">Přiřazení k řazené kolekci členů typu {0} vyžaduje dílčí vzory {1}, ale k dispozici jsou dílčí vzory {2}.</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidInputFileName"> <source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source> <target state="translated">Název souboru {0} je prázdný, obsahuje neplatné znaky, má specifikaci jednotky bez absolutní cesty nebo je moc dlouhý.</target> <note /> </trans-unit> <trans-unit id="IDS_AddressOfMethodGroup"> <source>&amp;method group</source> <target state="translated">skupina &amp;metod</target> <note /> </trans-unit> <trans-unit id="IDS_CSCHelp"> <source> Visual C# Compiler Options - OUTPUT FILES - -out:&lt;file&gt; Specify output file name (default: base name of file with main class or first file) -target:exe Build a console executable (default) (Short form: -t:exe) -target:winexe Build a Windows executable (Short form: -t:winexe) -target:library Build a library (Short form: -t:library) -target:module Build a module that can be added to another assembly (Short form: -t:module) -target:appcontainerexe Build an Appcontainer executable (Short form: -t:appcontainerexe) -target:winmdobj Build a Windows Runtime intermediate file that is consumed by WinMDExp (Short form: -t:winmdobj) -doc:&lt;file&gt; XML Documentation file to generate -refout:&lt;file&gt; Reference assembly output to generate -platform:&lt;string&gt; Limit which platforms this code can run on: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred, or anycpu. The default is anycpu. - INPUT FILES - -recurse:&lt;wildcard&gt; Include all files in the current directory and subdirectories according to the wildcard specifications -reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: -r) -reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: -r) -addmodule:&lt;file list&gt; Link the specified modules into this assembly -link:&lt;file list&gt; Embed metadata from the specified interop assembly files (Short form: -l) -analyzer:&lt;file list&gt; Run the analyzers from this assembly (Short form: -a) -additionalfile:&lt;file list&gt; Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings. -embed Embed all source files in the PDB. -embed:&lt;file list&gt; Embed specific files in the PDB. - RESOURCES - -win32res:&lt;file&gt; Specify a Win32 resource file (.res) -win32icon:&lt;file&gt; Use this icon for the output -win32manifest:&lt;file&gt; Specify a Win32 manifest file (.xml) -nowin32manifest Do not include the default Win32 manifest -resource:&lt;resinfo&gt; Embed the specified resource (Short form: -res) -linkresource:&lt;resinfo&gt; Link the specified resource to this assembly (Short form: -linkres) Where the resinfo format is &lt;file&gt;[,&lt;string name&gt;[,public|private]] - CODE GENERATION - -debug[+|-] Emit debugging information -debug:{full|pdbonly|portable|embedded} Specify debugging type ('full' is default, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the target .dll or .exe) -optimize[+|-] Enable optimizations (Short form: -o) -deterministic Produce a deterministic assembly (including module version GUID and timestamp) -refonly Produce a reference assembly in place of the main output -instrument:TestCoverage Produce an assembly instrumented to collect coverage information -sourcelink:&lt;file&gt; Source link info to embed into PDB. - ERRORS AND WARNINGS - -warnaserror[+|-] Report all warnings as errors -warnaserror[+|-]:&lt;warn list&gt; Report specific warnings as errors (use "nullable" for all nullability warnings) -warn:&lt;n&gt; Set warning level (0 or higher) (Short form: -w) -nowarn:&lt;warn list&gt; Disable specific warning messages (use "nullable" for all nullability warnings) -ruleset:&lt;file&gt; Specify a ruleset file that disables specific diagnostics. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Specify a file to log all compiler and analyzer diagnostics. sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 both mean SARIF version 2.1.0. -reportanalyzer Report additional analyzer information, such as execution time. -skipanalyzers[+|-] Skip execution of diagnostic analyzers. - LANGUAGE - -checked[+|-] Generate overflow checks -unsafe[+|-] Allow 'unsafe' code -define:&lt;symbol list&gt; Define conditional compilation symbol(s) (Short form: -d) -langversion:? Display the allowed values for language version -langversion:&lt;string&gt; Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` -nullable[+|-] Specify nullable context option enable|disable. -nullable:{enable|disable|warnings|annotations} Specify nullable context option enable|disable|warnings|annotations. - SECURITY - -delaysign[+|-] Delay-sign the assembly using only the public portion of the strong name key -publicsign[+|-] Public-sign the assembly using only the public portion of the strong name key -keyfile:&lt;file&gt; Specify a strong name key file -keycontainer:&lt;string&gt; Specify a strong name key container -highentropyva[+|-] Enable high-entropy ASLR - MISCELLANEOUS - @&lt;file&gt; Read response file for more options -help Display this usage message (Short form: -?) -nologo Suppress compiler copyright message -noconfig Do not auto include CSC.RSP file -parallel[+|-] Concurrent build. -version Display the compiler version number and exit. - ADVANCED - -baseaddress:&lt;address&gt; Base address for the library to be built -checksumalgorithm:&lt;alg&gt; Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default). -codepage:&lt;n&gt; Specify the codepage to use when opening source files -utf8output Output compiler messages in UTF-8 encoding -main:&lt;type&gt; Specify the type that contains the entry point (ignore all other possible entry points) (Short form: -m) -fullpaths Compiler generates fully qualified paths -filealign:&lt;n&gt; Specify the alignment used for output file sections -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Specify a mapping for source path names output by the compiler. -pdb:&lt;file&gt; Specify debug information file name (default: output file name with .pdb extension) -errorendlocation Output line and column of the end location of each error -preferreduilang Specify the preferred output language name. -nosdkpath Disable searching the default SDK path for standard library assemblies. -nostdlib[+|-] Do not reference standard library (mscorlib.dll) -subsystemversion:&lt;string&gt; Specify subsystem version of this assembly -lib:&lt;file list&gt; Specify additional directories to search in for references -errorreport:&lt;string&gt; Specify how to handle internal compiler errors: prompt, send, queue, or none. The default is queue. -appconfig:&lt;file&gt; Specify an application configuration file containing assembly binding settings -moduleassemblyname:&lt;string&gt; Name of the assembly which this module will be a part of -modulename:&lt;string&gt; Specify the name of the source module -generatedfilesout:&lt;dir&gt; Place files generated during compilation in the specified directory. </source> <target state="translated"> Parametry kompilátoru Visual C# - VÝSTUPNÍ SOUBORY - -out:&lt;file&gt; Určuje název výstupního souboru (výchozí: základní název souboru s hlavní třídou nebo prvního souboru) -target:exe Vytvoří spustitelný soubor konzoly (výchozí). (Krátký formát: -t:exe) -target:winexe Vytvoří spustitelný soubor systému Windows. (Krátký formát: -t:winexe) -target:library Vytvoří knihovnu. (Krátký formát: -t:library) -target:module Vytvoří modul, který se dá přidat do jiného sestavení. (Krátký formát: -t:module) -target:appcontainerexe Sestaví spustitelný soubor kontejneru Appcontainer. (Krátký formát: -t:appcontainerexe) -target:winmdobj Sestaví pomocný soubor modulu Windows Runtime, který využívá knihovna WinMDExp. (Krátký formát: -t:winmdobj) -doc:&lt;file&gt; Soubor dokumentace XML, který má být vygenerován -refout:&lt;file&gt; Výstup referenčního sestavení, který má být vygenerován -platform:&lt;string&gt; Omezuje platformy, na kterých lze tento kód spustit: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred nebo anycpu. Výchozí nastavení je anycpu. - VSTUPNÍ SOUBORY - -recurse:&lt;wildcard&gt; Zahrne všechny soubory v aktuálním adresáři a jeho podadresářích podle zadaného zástupného znaku. -reference:&lt;alias&gt;=&lt;file&gt; Odkazuje na metadata ze zadaného souboru sestavení pomocí daného aliasu. (Krátký formát: -r) -reference:&lt;file list&gt; Odkazuje na metadata ze zadaných souborů sestavení (Krátký formát: -r) -addmodule:&lt;file list&gt; Připojí zadané moduly k tomuto sestavení. -link:&lt;file list&gt; Vloží metadata ze zadaných souborů sestavení spolupráce (Krátký formát: -l) -analyzer:&lt;file list&gt; Spustí analyzátory z tohoto sestavení. (Krátký formát: -a) -additionalfile:&lt;file list&gt; Další soubory, které přímo neovlivňují generování kódu, ale analyzátory můžou jejich pomocí produkovat chyby nebo upozornění. -embed Vloží všechny zdrojové soubory do PDB. -embed:&lt;file list&gt; Vloží konkrétní soubory do PDB. - PROSTŘEDKY - -win32res:&lt;file&gt; Určuje soubor prostředků Win32 (.res). -win32icon:&lt;file&gt; Použije pro výstup zadanou ikonu. -win32manifest:&lt;file&gt; Určuje soubor manifestu Win32 (.xml). -nowin32manifest Nezahrne výchozí manifest Win32. -resource:&lt;resinfo&gt; Vloží zadaný prostředek. (Krátký formát: -res) -linkresource:&lt;resinfo&gt; Propojí zadaný prostředek s tímto sestavením. (Krátký formát: -linkres) Prostředek má formát is &lt;file&gt;[,&lt;string name&gt;[,public|private]]. - GENEROVÁNÍ KÓDU - -debug[+|-] Generuje ladicí informace. -debug:{full|pdbonly|portable|embedded} Určuje typ ladění (výchozí je možnost full, portable je formát napříč platformami, embedded je formát napříč platformami vložený do cílového souboru .dll nebo .exe). -optimize[+|-] Povolí optimalizace. (Krátký formát: -o) -deterministic Vytvoří deterministické sestavení (včetně GUID verze modulu a časového razítka). -refonly Vytvoří referenční sestavení na místě hlavního výstupu. -instrument:TestCoverage Vytvoří sestavení instrumentované ke shromažďování informací o pokrytí. -sourcelink:&lt;file&gt; Informace o zdrojovém odkazu vkládané do souboru PDB.. - CHYBY A UPOZORNĚNÍ - -warnaserror[+|-] Hlásí všechna upozornění jako chyby. -warnaserror[+|-]:&lt;warn list&gt; Hlásí zadaná upozornění jako chyby. (Pro všechna upozornění na možnost použití hodnoty null použijte nullable.) -warn:&lt;n&gt; Nastaví úroveň pro upozornění (0 a více). (Krátký formát: -w) -nowarn:&lt;warn list&gt; Zakáže zadaná upozornění. (Pro všechna upozornění na možnost použití hodnoty null použijte nullable.) -ruleset:&lt;file&gt; Určuje soubor sady pravidel, která zakazuje specifickou diagnostiku. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Určuje soubor pro protokolování veškeré diagnostiky kompilátoru a analyzátoru. verze_sarif:{1|2|2.1} Výchozí jsou 1. 2 a 2.1. Obojí znamená SARIF verze 2.1.0. -reportanalyzer Hlásí další informace analyzátoru, např. dobu spuštění. -skipanalyzers[+|-] Přeskočí spouštění diagnostických analyzátorů. - JAZYK - -checked[+|-] Generuje kontroly přetečení. -unsafe[+|-] Povoluje nezabezpečený kód. -define:&lt;symbol list&gt; Definuje symboly podmíněné kompilace. (Krátký formát: -d) -langversion:? Zobrazuje povolené hodnoty pro verzi jazyka. -langversion:&lt;string&gt; Určuje verzi jazyka, například: latest (poslední verze včetně podverzí), default (stejné jako latest), latestmajor (poslední verze bez podverzí), preview (poslední verze včetně funkcí v nepodporované verzi preview) nebo konkrétní verze, například 6 nebo 7.1. -nullable[+|-] Určuje pro kontext s hodnotou null možnosti enable|disable. -nullable:{enable|disable|warnings|annotations} Určuje pro kontext s hodnotou null možnosti enable|disable|warnings|annotations. - ZABEZPEČENÍ - -delaysign[+|-] Vytvoří zpožděný podpis sestavení s využitím jenom veřejné části klíče silného názvu. -publicsign[+|-] Vytvoří veřejný podpis sestavení s využitím jenom veřejné části klíče silného názvu. -keyfile:&lt;file&gt; Určuje soubor klíče se silným názvem. -keycontainer:&lt;string&gt; Určuje kontejner klíče se silným názvem. -highentropyva[+|-] Povolí ASLR s vysokou entropií. - RŮZNÉ - @&lt;file&gt; Načte další možnosti ze souboru odpovědí. -help Zobrazí tuto zprávu o použití. (Krátký formát: -?) -nologo Potlačí zprávu o autorských právech kompilátoru. -noconfig Nezahrnuje automaticky soubor CSC.RSP. -parallel[+|-] Souběžné sestavení. -version Zobrazí číslo verze kompilátoru a ukončí se. - POKROČILÉ - -baseaddress:&lt;address&gt; Základní adresa pro knihovnu, která se má sestavit. -checksumalgorithm:&lt;alg&gt; Určuje algoritmus pro výpočet kontrolního součtu zdrojového souboru uloženého v PDB. Podporované hodnoty: SHA1 nebo SHA256 (výchozí). -codepage:&lt;n&gt; Určuje znakovou stránku, která se má použít při otevírání zdrojových souborů. -utf8output Určuje výstup zpráv kompilátoru v kódování UTF-8. -main:&lt;typ&gt; Určuje typ obsahující vstupní bod (ignoruje všechny ostatní potenciální vstupní body). (Krátký formát: -m) -fullpaths Kompilátor generuje úplné cesty. -filealign:&lt;n&gt; Určuje zarovnání použité pro oddíly výstupního souboru. -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Určuje mapování pro výstup zdrojových názvů cest kompilátorem. -pdb:&lt;file&gt; Určuje název souboru ladicích informací (výchozí: název výstupního souboru s příponou .pdb). -errorendlocation Vypíše řádek a sloupec koncového umístění jednotlivých chyb. -preferreduilang Určuje název upřednostňovaného výstupního jazyka. -nosdkpath Zakazuje hledání cesty k výchozí sadě SDK pro sestavení standardních knihoven. -nostdlib[+|-] Neodkazuje na standardní knihovnu (mscorlib.dll). -subsystemversion:&lt;string&gt; Určuje verzi subsystému tohoto sestavení. -lib:&lt;file list&gt; Určuje další adresáře, ve kterých se mají hledat reference. -errorreport:&lt;řetězec&gt; Určuje způsob zpracování interních chyb kompilátoru: prompt, send, queue nebo none. Výchozí možnost je queue (zařadit do fronty). -appconfig:&lt;file&gt; Určuje konfigurační soubor aplikace, který obsahuje nastavení vazby sestavení. -moduleassemblyname:&lt;string&gt; Určuje název sestavení, jehož součástí bude tento modul. -modulename:&lt;string&gt; Určuje název zdrojového modulu. -generatedfilesout:&lt;dir&gt; Umístí soubory vygenerované během kompilace do zadaného adresáře. </target> <note>Visual C# Compiler Options</note> </trans-unit> <trans-unit id="IDS_DefaultInterfaceImplementation"> <source>default interface implementation</source> <target state="translated">implementace výchozího rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_Disposable"> <source>disposable</source> <target state="translated">jednoúčelové</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAltInterpolatedVerbatimStrings"> <source>alternative interpolated verbatim strings</source> <target state="translated">alternativní interpolované doslovné řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAndPattern"> <source>and pattern</source> <target state="translated">vzor and</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncUsing"> <source>asynchronous using</source> <target state="translated">asynchronní příkaz using</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCoalesceAssignmentExpression"> <source>coalescing assignment</source> <target state="translated">slučovací přiřazení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureConstantInterpolatedStrings"> <source>constant interpolated strings</source> <target state="translated">konstantní interpolované řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefaultTypeParameterConstraint"> <source>default type parameter constraints</source> <target state="translated">výchozí omezení parametru typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDelegateGenericTypeConstraint"> <source>delegate generic type constraints</source> <target state="translated">delegovat obecná omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureEnumGenericTypeConstraint"> <source>enum generic type constraints</source> <target state="translated">výčet obecných omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionVariablesInQueriesAndInitializers"> <source>declaration of expression variables in member initializers and queries</source> <target state="translated">deklarace proměnných výrazu v inicializátorech členů a dotazech</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtendedPartialMethods"> <source>extended partial methods</source> <target state="translated">rozšířené částečné metody</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensibleFixedStatement"> <source>extensible fixed statement</source> <target state="translated">rozšiřitelný příkaz fixed</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionGetAsyncEnumerator"> <source>extension GetAsyncEnumerator</source> <target state="translated">rozšíření GetAsyncEnumerator</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionGetEnumerator"> <source>extension GetEnumerator</source> <target state="translated">rozšíření GetEnumerator</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExternLocalFunctions"> <source>extern local functions</source> <target state="translated">externí místní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFunctionPointers"> <source>function pointers</source> <target state="translated">ukazatele na funkci</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIndexOperator"> <source>index operator</source> <target state="translated">operátor indexu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIndexingMovableFixedBuffers"> <source>indexing movable fixed buffers</source> <target state="translated">indexování mobilních vyrovnávacích pamětí pevné velikosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInitOnlySetters"> <source>init-only setters</source> <target state="translated">metody setter jenom pro inicializaci</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLocalFunctionAttributes"> <source>local function attributes</source> <target state="translated">atributy místních funkcí</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaDiscardParameters"> <source>lambda discard parameters</source> <target state="translated">lambda – zahodit parametry</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureMemberNotNull"> <source>MemberNotNull attribute</source> <target state="translated">Atribut MemberNotNull</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureModuleInitializers"> <source>module initializers</source> <target state="translated">inicializátory modulů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNameShadowingInNestedFunctions"> <source>name shadowing in nested functions</source> <target state="translated">skrývání názvů ve vnořených funkcích</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNativeInt"> <source>native-sized integers</source> <target state="translated">Celá čísla s nativní velikostí</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNestedStackalloc"> <source>stackalloc in nested expressions</source> <target state="translated">stackalloc ve vnořených výrazech</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNotNullGenericTypeConstraint"> <source>notnull generic type constraint</source> <target state="translated">omezení obecného typu notnull</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNotPattern"> <source>not pattern</source> <target state="translated">vzor not</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullPointerConstantPattern"> <source>null pointer constant pattern</source> <target state="translated">konstantní vzor nulového ukazatele</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullableReferenceTypes"> <source>nullable reference types</source> <target state="translated">typy odkazů s možnou hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureObsoleteOnPropertyAccessor"> <source>obsolete on property accessor</source> <target state="translated">zastaralé u přístupového objektu vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOrPattern"> <source>or pattern</source> <target state="translated">vzor or</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureParenthesizedPattern"> <source>parenthesized pattern</source> <target state="translated">vzor se závorkami</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePragmaWarningEnable"> <source>warning action enable</source> <target state="translated">akce upozornění enable</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRangeOperator"> <source>range operator</source> <target state="translated">operátor rozsahu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyMembers"> <source>readonly members</source> <target state="translated">členové s modifikátorem readonly</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecords"> <source>records</source> <target state="translated">záznamy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecursivePatterns"> <source>recursive patterns</source> <target state="translated">rekurzivní vzory</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefConditional"> <source>ref conditional expression</source> <target state="translated">referenční podmínka</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefFor"> <source>ref for-loop variables</source> <target state="translated">Proměnné smyčky for odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefForEach"> <source>ref foreach iteration variables</source> <target state="translated">Iterační proměnné foreach odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefReassignment"> <source>ref reassignment</source> <target state="translated">Opětovné přiřazení odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRelationalPattern"> <source>relational pattern</source> <target state="translated">relační vzor</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStackAllocInitializer"> <source>stackalloc initializer</source> <target state="translated">inicializátor výrazu stackalloc</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticAnonymousFunction"> <source>static anonymous function</source> <target state="translated">statická anonymní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticLocalFunctions"> <source>static local functions</source> <target state="translated">statické místní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureSwitchExpression"> <source>&lt;switch expression&gt;</source> <target state="translated">&lt;výraz přepínače&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTargetTypedConditional"> <source>target-typed conditional expression</source> <target state="translated">podmíněný výraz s typem cíle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTupleEquality"> <source>tuple equality</source> <target state="translated">rovnost řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTypePattern"> <source>type pattern</source> <target state="translated">vzor typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator"> <source>unconstrained type parameters in null coalescing operator</source> <target state="translated">parametry neomezeného typu v operátoru sloučení s hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnmanagedConstructedTypes"> <source>unmanaged constructed types</source> <target state="translated">nespravované konstruované typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnmanagedGenericTypeConstraint"> <source>unmanaged generic type constraints</source> <target state="translated">nespravovaná obecná omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUsingDeclarations"> <source>using declarations</source> <target state="translated">deklarace using</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureVarianceSafetyForStaticInterfaceMembers"> <source>variance safety for static interface members</source> <target state="translated">zabezpečení odchylky pro statické členy rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_NULL"> <source>&lt;null&gt;</source> <target state="translated">&lt;null&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_OverrideWithConstraints"> <source>constraints for override and explicit interface implementation methods</source> <target state="translated">omezení pro metody přepsání a explicitní implementace rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_Parameter"> <source>parameter</source> <target state="translated">parametr</target> <note /> </trans-unit> <trans-unit id="IDS_Return"> <source>return</source> <target state="translated">návratový</target> <note /> </trans-unit> <trans-unit id="IDS_ThrowExpression"> <source>&lt;throw expression&gt;</source> <target state="translated">&lt;výraz throw&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_RELATEDERROR"> <source>(Location of symbol related to previous error)</source> <target state="translated">(Umístění symbolu vzhledem k předchozí chybě)</target> <note /> </trans-unit> <trans-unit id="IDS_RELATEDWARNING"> <source>(Location of symbol related to previous warning)</source> <target state="translated">(Umístění symbolu vzhledem k předchozímu upozornění)</target> <note /> </trans-unit> <trans-unit id="IDS_TopLevelStatements"> <source>top-level statements</source> <target state="translated">příkazy nejvyšší úrovně</target> <note /> </trans-unit> <trans-unit id="IDS_XMLIGNORED"> <source>&lt;!-- Badly formed XML comment ignored for member "{0}" --&gt;</source> <target state="translated">&lt;!-- Badly formed XML comment ignored for member "{0}" --&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_XMLIGNORED2"> <source> Badly formed XML file "{0}" cannot be included </source> <target state="translated"> Chybně vytvořený soubor XML {0} nejde zahrnout. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLFAILEDINCLUDE"> <source> Failed to insert some or all of included XML </source> <target state="translated"> Vložení části nebo veškerého zahrnutého kódu XML se nezdařilo. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLBADINCLUDE"> <source> Include tag is invalid </source> <target state="translated"> Značka Include je neplatná. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLNOINCLUDE"> <source> No matching elements were found for the following include tag </source> <target state="translated"> Pro následující značku include se nenašly žádné vyhovující prvky. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLMISSINGINCLUDEFILE"> <source>Missing file attribute</source> <target state="translated">Atribut souboru se nenašel.</target> <note /> </trans-unit> <trans-unit id="IDS_XMLMISSINGINCLUDEPATH"> <source>Missing path attribute</source> <target state="translated">Atribut cesty se nenašel.</target> <note /> </trans-unit> <trans-unit id="IDS_GlobalNamespace"> <source>&lt;global namespace&gt;</source> <target state="translated">&lt;globální obor názvů&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGenerics"> <source>generics</source> <target state="translated">obecné</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAnonDelegates"> <source>anonymous methods</source> <target state="translated">anonymní metody</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureModuleAttrLoc"> <source>module as an attribute target specifier</source> <target state="translated">modul jako cílový specifikátor atributů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGlobalNamespace"> <source>namespace alias qualifier</source> <target state="translated">kvalifikátor aliasu oboru názvů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFixedBuffer"> <source>fixed size buffers</source> <target state="translated">vyrovnávací paměti pevné velikosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePragma"> <source>#pragma</source> <target state="translated">#pragma</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticClasses"> <source>static classes</source> <target state="translated">statické třídy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyStructs"> <source>readonly structs</source> <target state="translated">struktury jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePartialTypes"> <source>partial types</source> <target state="translated">částečné typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsync"> <source>async function</source> <target state="translated">asynchronní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureSwitchOnBool"> <source>switch on boolean type</source> <target state="translated">přepínač založený na typu boolean</target> <note /> </trans-unit> <trans-unit id="IDS_MethodGroup"> <source>method group</source> <target state="translated">skupina metod</target> <note /> </trans-unit> <trans-unit id="IDS_AnonMethod"> <source>anonymous method</source> <target state="translated">anonymní metoda</target> <note /> </trans-unit> <trans-unit id="IDS_Lambda"> <source>lambda expression</source> <target state="translated">výraz lambda</target> <note /> </trans-unit> <trans-unit id="IDS_Collection"> <source>collection</source> <target state="translated">kolekce</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePropertyAccessorMods"> <source>access modifiers on properties</source> <target state="translated">modifikátory přístupu pro vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExternAlias"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIterators"> <source>iterators</source> <target state="translated">iterátory</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefault"> <source>default operator</source> <target state="translated">výchozí operátor</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefaultLiteral"> <source>default literal</source> <target state="translated">výchozí literál</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePrivateProtected"> <source>private protected</source> <target state="translated">private protected</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullable"> <source>nullable types</source> <target state="translated">typy s povolenou hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePatternMatching"> <source>pattern matching</source> <target state="translated">porovnávání vzorů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedAccessor"> <source>expression body property accessor</source> <target state="translated">přístupový objekt vlastnosti textu výrazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedDeOrConstructor"> <source>expression body constructor and destructor</source> <target state="translated">konstruktor a destruktor textu výrazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureThrowExpression"> <source>throw expression</source> <target state="translated">výraz throw</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitArray"> <source>implicitly typed array</source> <target state="translated">implicitně typované pole</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitLocal"> <source>implicitly typed local variable</source> <target state="translated">implicitně typovaná lokální proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAnonymousTypes"> <source>anonymous types</source> <target state="translated">anonymní typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAutoImplementedProperties"> <source>automatically implemented properties</source> <target state="translated">automaticky implementované vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadonlyAutoImplementedProperties"> <source>readonly automatically implemented properties</source> <target state="translated">automaticky implementované vlastnosti jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureObjectInitializer"> <source>object initializer</source> <target state="translated">inicializátor objektu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCollectionInitializer"> <source>collection initializer</source> <target state="translated">inicializátor kolekce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureQueryExpression"> <source>query expression</source> <target state="translated">výraz dotazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionMethod"> <source>extension method</source> <target state="translated">metoda rozšíření</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePartialMethod"> <source>partial method</source> <target state="translated">částečná metoda</target> <note /> </trans-unit> <trans-unit id="IDS_SK_METHOD"> <source>method</source> <target state="translated">metoda</target> <note /> </trans-unit> <trans-unit id="IDS_SK_TYPE"> <source>type</source> <target state="translated">typ</target> <note /> </trans-unit> <trans-unit id="IDS_SK_NAMESPACE"> <source>namespace</source> <target state="translated">obor názvů</target> <note /> </trans-unit> <trans-unit id="IDS_SK_FIELD"> <source>field</source> <target state="translated">pole</target> <note /> </trans-unit> <trans-unit id="IDS_SK_PROPERTY"> <source>property</source> <target state="translated">vlastnost</target> <note /> </trans-unit> <trans-unit id="IDS_SK_UNKNOWN"> <source>element</source> <target state="translated">element</target> <note /> </trans-unit> <trans-unit id="IDS_SK_VARIABLE"> <source>variable</source> <target state="translated">proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_SK_LABEL"> <source>label</source> <target state="translated">popisek</target> <note /> </trans-unit> <trans-unit id="IDS_SK_EVENT"> <source>event</source> <target state="translated">událost</target> <note /> </trans-unit> <trans-unit id="IDS_SK_TYVAR"> <source>type parameter</source> <target state="translated">parametr typu</target> <note /> </trans-unit> <trans-unit id="IDS_SK_ALIAS"> <source>using alias</source> <target state="translated">alias using</target> <note /> </trans-unit> <trans-unit id="IDS_SK_EXTERNALIAS"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="IDS_SK_CONSTRUCTOR"> <source>constructor</source> <target state="translated">konstruktor</target> <note /> </trans-unit> <trans-unit id="IDS_FOREACHLOCAL"> <source>foreach iteration variable</source> <target state="translated">iterační proměnná foreach</target> <note /> </trans-unit> <trans-unit id="IDS_FIXEDLOCAL"> <source>fixed variable</source> <target state="translated">pevná proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_USINGLOCAL"> <source>using variable</source> <target state="translated">proměnná using</target> <note /> </trans-unit> <trans-unit id="IDS_Contravariant"> <source>contravariant</source> <target state="translated">kontravariant</target> <note /> </trans-unit> <trans-unit id="IDS_Contravariantly"> <source>contravariantly</source> <target state="translated">kontravariantně</target> <note /> </trans-unit> <trans-unit id="IDS_Covariant"> <source>covariant</source> <target state="translated">kovariant</target> <note /> </trans-unit> <trans-unit id="IDS_Covariantly"> <source>covariantly</source> <target state="translated">kovariantně</target> <note /> </trans-unit> <trans-unit id="IDS_Invariantly"> <source>invariantly</source> <target state="translated">invariantně</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDynamic"> <source>dynamic</source> <target state="translated">dynamický</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNamedArgument"> <source>named argument</source> <target state="translated">pojmenovaný argument</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOptionalParameter"> <source>optional parameter</source> <target state="translated">volitelný parametr</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExceptionFilter"> <source>exception filter</source> <target state="translated">filtr výjimky</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTypeVariance"> <source>type variance</source> <target state="translated">odchylka typu</target> <note /> </trans-unit> <trans-unit id="NotSameNumberParameterTypesAndRefKinds"> <source>Given {0} parameter types and {1} parameter ref kinds. These arrays must have the same length.</source> <target state="translated">Předal se určitý počet parametrů ({0}) a jiný počet druhů odkazů na parametry ({1}). Tato pole musí být stejně velká.</target> <note /> </trans-unit> <trans-unit id="OutIsNotValidForReturn"> <source>'RefKind.Out' is not a valid ref kind for a return type.</source> <target state="translated">RefKind.Out není platný druh odkazu pro návratový typ.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFound"> <source>SyntaxTree is not part of the compilation</source> <target state="translated">SyntaxTree není součástí kompilace.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFoundToRemove"> <source>SyntaxTree is not part of the compilation, so it cannot be removed</source> <target state="translated">SyntaxTree není součástí kompilace, takže se nedá odebrat.</target> <note /> </trans-unit> <trans-unit id="WRN_CaseConstantNamedUnderscore"> <source>The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.</source> <target state="translated">Název „_“ odkazuje na konstantu, ne na vzor discard. Zadáním „var _“ hodnotu zahodíte a zadáním „@_“ nastavíte pod tímto názvem odkaz na konstantu.</target> <note /> </trans-unit> <trans-unit id="WRN_CaseConstantNamedUnderscore_Title"> <source>Do not use '_' for a case constant.</source> <target state="translated">Nepoužívejte „_“ jako konstantu case.</target> <note /> </trans-unit> <trans-unit id="WRN_ConstOutOfRangeChecked"> <source>Constant value '{0}' may overflow '{1}' at runtime (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnota {0} může při běhu přetéct {1} (pro přepis použijte syntaxi unchecked).</target> <note /> </trans-unit> <trans-unit id="WRN_ConstOutOfRangeChecked_Title"> <source>Constant value may overflow at runtime (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnota může při běhu přetéct (pro přepis použijte syntaxi unchecked)</target> <note /> </trans-unit> <trans-unit id="WRN_ConvertingNullableToNonNullable"> <source>Converting null literal or possible null value to non-nullable type.</source> <target state="translated">Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_ConvertingNullableToNonNullable_Title"> <source>Converting null literal or possible null value to non-nullable type.</source> <target state="translated">Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_DisallowNullAttributeForbidsMaybeNullAssignment"> <source>A possible null value may not be used for a type marked with [NotNull] or [DisallowNull]</source> <target state="translated">Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull].</target> <note /> </trans-unit> <trans-unit id="WRN_DisallowNullAttributeForbidsMaybeNullAssignment_Title"> <source>A possible null value may not be used for a type marked with [NotNull] or [DisallowNull]</source> <target state="translated">Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull].</target> <note /> </trans-unit> <trans-unit id="WRN_DoesNotReturnMismatch"> <source>Method '{0}' lacks `[DoesNotReturn]` annotation to match implemented or overridden member.</source> <target state="translated">Metodě {0} chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_DoesNotReturnMismatch_Title"> <source>Method lacks `[DoesNotReturn]` annotation to match implemented or overridden member.</source> <target state="translated">Metodě chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList"> <source>'{0}' is already listed in the interface list on type '{1}' with different nullability of reference types.</source> <target state="translated">Položka {0} je už uvedená v seznamu rozhraní u typu {1} s různou možností použití hodnoty null u typů odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList_Title"> <source>Interface is already listed in the interface list with different nullability of reference types.</source> <target state="translated">Rozhraní je už uvedené v seznamu rozhraní s různou možností použití hodnoty null u typů odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration"> <source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">Generátor {0} nemohl vygenerovat zdroj. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}.</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">Generátor vyvolal následující výjimku: {0}.</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Title"> <source>Generator failed to generate source.</source> <target state="translated">Generátoru se nepovedlo vygenerovat zdroj</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization"> <source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">Generátor {0} se nepovedlo inicializovat. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}.</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">Generátor vyvolal následující výjimku: {0}.</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Title"> <source>Generator failed to initialize.</source> <target state="translated">Generátor se nepovedlo inicializovat</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesConstant"> <source>The given expression always matches the provided constant.</source> <target state="translated">Daný výraz vždy odpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesConstant_Title"> <source>The given expression always matches the provided constant.</source> <target state="translated">Daný výraz vždy odpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesPattern"> <source>The given expression always matches the provided pattern.</source> <target state="translated">Daný výraz vždy odpovídá zadanému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesPattern_Title"> <source>The given expression always matches the provided pattern.</source> <target state="translated">Daný výraz vždy odpovídá zadanému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionNeverMatchesPattern"> <source>The given expression never matches the provided pattern.</source> <target state="translated">Daný výraz nikdy neodpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionNeverMatchesPattern_Title"> <source>The given expression never matches the provided pattern.</source> <target state="translated">Daný výraz nikdy neodpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitCopyInReadOnlyMember"> <source>Call to non-readonly member '{0}' from a 'readonly' member results in an implicit copy of '{1}'.</source> <target state="translated">Volání člena {0}, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitCopyInReadOnlyMember_Title"> <source>Call to non-readonly member from a 'readonly' member results in an implicit copy.</source> <target state="translated">Volání člena, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii.</target> <note /> </trans-unit> <trans-unit id="WRN_IsPatternAlways"> <source>An expression of type '{0}' always matches the provided pattern.</source> <target state="translated">Výraz typu {0} vždy odpovídá poskytnutému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_IsPatternAlways_Title"> <source>The input always matches the provided pattern.</source> <target state="translated">Vstup vždy odpovídá zadanému vzoru</target> <note /> </trans-unit> <trans-unit id="WRN_IsTypeNamedUnderscore"> <source>The name '_' refers to the type '{0}', not the discard pattern. Use '@_' for the type, or 'var _' to discard.</source> <target state="translated">Název „_“ odkazuje na typ {0}, ne vzor discard. Použijte „@_“ pro tento typ nebo „var _“ pro zahození.</target> <note /> </trans-unit> <trans-unit id="WRN_IsTypeNamedUnderscore_Title"> <source>Do not use '_' to refer to the type in an is-type expression.</source> <target state="translated">Nepoužívejte „_“ jako odkaz na typ ve výrazu is-type.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNull"> <source>Member '{0}' must have a non-null value when exiting.</source> <target state="translated">Člen {0} musí mít při ukončení hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullBadMember"> <source>Member '{0}' cannot be used in this attribute.</source> <target state="translated">Člen {0} se v tomto atributu nedá použít.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullBadMember_Title"> <source>Member cannot be used in this attribute.</source> <target state="translated">Člen se v tomto atributu nedá použít.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullWhen"> <source>Member '{0}' must have a non-null value when exiting with '{1}'.</source> <target state="translated">Člen {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullWhen_Title"> <source>Member must have a non-null value when exiting in some condition.</source> <target state="translated">Člen musí mít při ukončení za určité podmínky hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNull_Title"> <source>Member must have a non-null value when exiting.</source> <target state="translated">Člen musí mít při ukončení hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotation"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.</source> <target state="translated">Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.</source> <target state="translated">Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode_Title"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.</source> <target state="translated">Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotation_Title"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.</source> <target state="translated">Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable.</target> <note /> </trans-unit> <trans-unit id="WRN_NullAsNonNullable"> <source>Cannot convert null literal to non-nullable reference type.</source> <target state="translated">Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullAsNonNullable_Title"> <source>Cannot convert null literal to non-nullable reference type.</source> <target state="translated">Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceArgument"> <source>Possible null reference argument for parameter '{0}' in '{1}'.</source> <target state="translated">V parametru {0} v {1} může být argument s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceArgument_Title"> <source>Possible null reference argument.</source> <target state="translated">Může jít o argument s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceAssignment"> <source>Possible null reference assignment.</source> <target state="translated">Může jít o přiřazení s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceAssignment_Title"> <source>Possible null reference assignment.</source> <target state="translated">Může jít o přiřazení s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceInitializer"> <source>Object or collection initializer implicitly dereferences possibly null member '{0}'.</source> <target state="translated">Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi {0}, který může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceInitializer_Title"> <source>Object or collection initializer implicitly dereferences possibly null member.</source> <target state="translated">Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi, který může být null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReceiver"> <source>Dereference of a possibly null reference.</source> <target state="translated">Přístup přes ukazatel k možnému odkazu s hodnotou null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReceiver_Title"> <source>Dereference of a possibly null reference.</source> <target state="translated">Přístup přes ukazatel k možnému odkazu s hodnotou null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReturn"> <source>Possible null reference return.</source> <target state="translated">Může jít o vrácený odkaz null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReturn_Title"> <source>Possible null reference return.</source> <target state="translated">Může jít o vrácený odkaz null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgument"> <source>Argument of type '{0}' cannot be used for parameter '{2}' of type '{1}' in '{3}' due to differences in the nullability of reference types.</source> <target state="translated">Argument typu {0} nejde použít pro parametr {2} typu {1} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgumentForOutput"> <source>Argument of type '{0}' cannot be used as an output of type '{1}' for parameter '{2}' in '{3}' due to differences in the nullability of reference types.</source> <target state="translated">Argument typu {0} nejde použít jako výstup typu {1} pro parametr {2} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgumentForOutput_Title"> <source>Argument cannot be used as an output for parameter due to differences in the nullability of reference types.</source> <target state="translated">Argument nejde použít jako výstup pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgument_Title"> <source>Argument cannot be used for parameter due to differences in the nullability of reference types.</source> <target state="translated">Argument nejde použít pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInAssignment"> <source>Nullability of reference types in value of type '{0}' doesn't match target type '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v hodnotě typu {0} neodpovídá cílovému typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInAssignment_Title"> <source>Nullability of reference types in value doesn't match target type.</source> <target state="translated">Typ odkazu s možnou hodnotou null v hodnotě neodpovídá cílovému typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnImplicitImplementation"> <source>Nullability in constraints for type parameter '{0}' of method '{1}' doesn't match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead.</source> <target state="translated">Možná hodnota null v omezení parametru typu {0} metody {1} neodpovídá omezením parametru typu {2} metody rozhraní {3}. Zkuste raději použít explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnImplicitImplementation_Title"> <source>Nullability in constraints for type parameter doesn't match the constraints for type parameter in implicitly implemented interface method'.</source> <target state="translated">Možná hodnota null v omezeních parametru typu neodpovídá omezením parametru typu v implicitně implementované metodě rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnPartialImplementation"> <source>Partial method declarations of '{0}' have inconsistent nullability in constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace metod {0} mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnPartialImplementation_Title"> <source>Partial method declarations have inconsistent nullability in constraints for type parameter</source> <target state="translated">Částečné deklarace metod mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInExplicitlyImplementedInterface"> <source>Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.</source> <target state="translated">Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInExplicitlyImplementedInterface_Title"> <source>Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.</source> <target state="translated">Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInInterfaceImplementedByBase"> <source>'{0}' does not implement interface member '{1}'. Nullability of reference types in interface implemented by the base type doesn't match.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInInterfaceImplementedByBase_Title"> <source>Type does not implement interface member. Nullability of reference types in interface implemented by the base type doesn't match.</source> <target state="translated">Typ neimplementuje člen rozhraní. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOfTargetDelegate"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match the target delegate '{2}' (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v typu parametru {0} z {1} neodpovídají cílovému delegátu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOfTargetDelegate_Title"> <source>Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v typu parametru neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnOverride"> <source>Nullability of reference types in type of parameter '{0}' doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnOverride_Title"> <source>Nullability of reference types in type of parameter doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnPartial"> <source>Nullability of reference types in type of parameter '{0}' doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnPartial_Title"> <source>Nullability of reference types in type of parameter doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOfTargetDelegate"> <source>Nullability of reference types in return type of '{0}' doesn't match the target delegate '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v návratovém typu {0} neodpovídají cílovému delegátu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOfTargetDelegate_Title"> <source>Nullability of reference types in return type doesn't match the target delegate (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v návratovém typu neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation"> <source>Nullability of reference types in return type doesn't match implemented member '{0}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation"> <source>Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnOverride"> <source>Nullability of reference types in return type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnOverride_Title"> <source>Nullability of reference types in return type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnPartial"> <source>Nullability of reference types in return type doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnPartial_Title"> <source>Nullability of reference types in return type doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnExplicitImplementation"> <source>Nullability of reference types in type doesn't match implemented member '{0}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnImplicitImplementation"> <source>Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu {0} neodpovídá implicitně implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnOverride"> <source>Nullability of reference types in type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnOverride_Title"> <source>Nullability of reference types in type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterConstraint"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. Nullability of type argument '{3}' doesn't match constraint type '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ argumentu {3} s možnou hodnotou null neodpovídá typu omezení {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match constraint type.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá typu omezení.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterNotNullConstraint"> <source>The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'notnull' constraint.</source> <target state="translated">Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Argument typu {2} s možnou hodnotou null neodpovídá omezení notnull.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterNotNullConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Argument typu s možnou hodnotou null neodpovídá omezení notnull.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint"> <source>The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'class' constraint.</source> <target state="translated">Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Typ argumentu {2} s možnou hodnotou null neodpovídá omezení třídy.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá omezení třídy.</target> <note /> </trans-unit> <trans-unit id="WRN_NullableValueTypeMayBeNull"> <source>Nullable value type may be null.</source> <target state="translated">Typ hodnoty, která připouští hodnotu null, nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullableValueTypeMayBeNull_Title"> <source>Nullable value type may be null.</source> <target state="translated">Typ hodnoty, která připouští hodnotu null, nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParamUnassigned"> <source>The out parameter '{0}' must be assigned to before control leaves the current method</source> <target state="translated">Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení.</target> <note /> </trans-unit> <trans-unit id="WRN_ParamUnassigned_Title"> <source>An out parameter must be assigned to before control leaves the method</source> <target state="translated">Parametr out se musí přiřadit ještě předtím, než metoda předá řízení</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterConditionallyDisallowsNull"> <source>Parameter '{0}' must have a non-null value when exiting with '{1}'.</source> <target state="translated">Parametr {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterConditionallyDisallowsNull_Title"> <source>Parameter must have a non-null value when exiting in some condition.</source> <target state="translated">Parametr musí mít při ukončení za určité podmínky hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterDisallowsNull"> <source>Parameter '{0}' must have a non-null value when exiting.</source> <target state="translated">Parametr {0} musí mít při ukončení hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterDisallowsNull_Title"> <source>Parameter must have a non-null value when exiting.</source> <target state="translated">Parametr musí mít při ukončení hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterIsStaticClass"> <source>'{0}': static types cannot be used as parameters</source> <target state="translated">{0}: Statické typy nejde používat jako parametry.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterIsStaticClass_Title"> <source>Static types cannot be used as parameters</source> <target state="translated">Statické typy se nedají používat jako parametry</target> <note /> </trans-unit> <trans-unit id="WRN_PrecedenceInversion"> <source>Operator '{0}' cannot be used here due to precedence. Use parentheses to disambiguate.</source> <target state="translated">Operátor {0} se tady nedá použít kvůli prioritám. Odstraňte nejednoznačnost pomocí závorek.</target> <note /> </trans-unit> <trans-unit id="WRN_PrecedenceInversion_Title"> <source>Operator cannot be used here due to precedence.</source> <target state="translated">Operátor se tady nedá použít kvůli prioritám</target> <note /> </trans-unit> <trans-unit id="WRN_PatternNotPublicOrNotInstance"> <source>'{0}' does not implement the '{1}' pattern. '{2}' is not a public instance or extension method.</source> <target state="translated">{0} neimplementuje vzor {1}. {2} není veřejná metoda instance nebo rozšíření.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternNotPublicOrNotInstance_Title"> <source>Type does not implement the collection pattern; member is is not a public instance or extension method.</source> <target state="translated">Typ neimplementuje vzor kolekce. Člen není veřejná metoda instance nebo rozšíření</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeIsStaticClass"> <source>'{0}': static types cannot be used as return types</source> <target state="translated">{0}: Statické typy nejde používat jako typy vracených hodnot.</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeIsStaticClass_Title"> <source>Static types cannot be used as return types</source> <target state="translated">Statické typy se nedají používat jako typy vracených hodnot</target> <note /> </trans-unit> <trans-unit id="WRN_ShouldNotReturn"> <source>A method marked [DoesNotReturn] should not return.</source> <target state="translated">Metoda označená jako [DoesNotReturn] by neměla vracet hodnotu</target> <note /> </trans-unit> <trans-unit id="WRN_ShouldNotReturn_Title"> <source>A method marked [DoesNotReturn] should not return.</source> <target state="translated">Metoda označená jako [DoesNotReturn] by se neměla ukončit standardním způsobem</target> <note /> </trans-unit> <trans-unit id="WRN_StaticInAsOrIs"> <source>The second operand of an 'is' or 'as' operator may not be static type '{0}'</source> <target state="translated">Druhý operand operátoru is nebo as nesmí být statického typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_StaticInAsOrIs_Title"> <source>The second operand of an 'is' or 'as' operator may not be a static type</source> <target state="translated">Druhý operand operátoru is nebo as nesmí být statického typu</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustive"> <source>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.</source> <target state="translated">Výraz switch nezachycuje všechny možné hodnoty vstupního typu (není úplný). Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNull"> <source>The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered.</source> <target state="translated">Výraz switch nezachycuje všechny některé vstupy null (není úplný). Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNullWithWhen"> <source>The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered. However, a pattern with a 'when' clause might successfully match this value.</source> <target state="translated">Výraz switch nezpracovává některé vstupy null (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNullWithWhen_Title"> <source>The switch expression does not handle some null inputs.</source> <target state="translated">Výraz switch nezpracovává některé vstupy s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNull_Title"> <source>The switch expression does not handle some null inputs.</source> <target state="translated">Výraz switch nezpracovává některé vstupy s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithWhen"> <source>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.</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty typu svého vstupu (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithWhen_Title"> <source>The switch expression does not handle all possible values of its input type (it is not exhaustive).</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný).</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustive_Title"> <source>The switch expression does not handle all possible values of its input type (it is not exhaustive).</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný)</target> <note /> </trans-unit> <trans-unit id="WRN_ThrowPossibleNull"> <source>Thrown value may be null.</source> <target state="translated">Vyvolaná hodnota může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_ThrowPossibleNull_Title"> <source>Thrown value may be null.</source> <target state="translated">Vyvolaná hodnota může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride"> <source>Nullability of type of parameter '{0}' doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u typu parametru {0} neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride_Title"> <source>Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u typu parametru neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation"> <source>Nullability of reference types in return type doesn't match implemented member '{0}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation"> <source>Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implicitly implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride"> <source>Nullability of return type doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride_Title"> <source>Nullability of return type doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TupleBinopLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified on the other side of the tuple == or != operator.</source> <target state="translated">Název elementu řazené kolekce členů {0} se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleBinopLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified on the other side of the tuple == or != operator.</source> <target state="translated">Název elementu řazené kolekce členů se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterMethodTypeParameter"> <source>Type parameter '{0}' has the same name as the type parameter from outer method '{1}'</source> <target state="translated">Parametr typu {0} má stejný název jako parametr typu z vnější metody {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterMethodTypeParameter_Title"> <source>Type parameter has the same type as the type parameter from outer method.</source> <target state="translated">Parametr typu má stejný typ jako parametr typu z vnější metody.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThis"> <source>Field '{0}' must be fully assigned before control is returned to the caller</source> <target state="translated">Před předáním řízení volající proceduře musí být pole {0} plně přiřazené.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThisAutoProperty"> <source>Auto-implemented property '{0}' must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu modulu musí být plně přiřazená automaticky implementovaná vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThisAutoProperty_Title"> <source>An auto-implemented property must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu se musí plně přiřadit automaticky implementovaná vlastnost</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThis_Title"> <source>Fields of a struct must be fully assigned in a constructor before control is returned to the caller</source> <target state="translated">Před vrácením řízení volajícímu se musí v konstruktoru plně přiřadit pole struktury</target> <note /> </trans-unit> <trans-unit id="WRN_UnboxPossibleNull"> <source>Unboxing a possibly null value.</source> <target state="translated">Rozbalení možné hodnoty null</target> <note /> </trans-unit> <trans-unit id="WRN_UnboxPossibleNull_Title"> <source>Unboxing a possibly null value.</source> <target state="translated">Rozbalení možné hodnoty null</target> <note /> </trans-unit> <trans-unit id="WRN_UnconsumedEnumeratorCancellationAttributeUsage"> <source>The EnumeratorCancellationAttribute applied to parameter '{0}' will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable</source> <target state="translated">EnumeratorCancellationAttribute, který se používá u parametru {0}, nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable.</target> <note /> </trans-unit> <trans-unit id="WRN_UnconsumedEnumeratorCancellationAttributeUsage_Title"> <source>The EnumeratorCancellationAttribute will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable</source> <target state="translated">EnumeratorCancellationAttribute nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable.</target> <note /> </trans-unit> <trans-unit id="WRN_UndecoratedCancellationTokenParameter"> <source>Async-iterator '{0}' has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator' will be unconsumed</source> <target state="translated">Asynchronní iterátor {0} má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator se nespotřebuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UndecoratedCancellationTokenParameter_Title"> <source>Async-iterator member has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator' will be unconsumed</source> <target state="translated">Člen asynchronního iterátoru má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator se nespotřebuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UninitializedNonNullableField"> <source>Non-nullable {0} '{1}' must contain a non-null value when exiting constructor. Consider declaring the {0} as nullable.</source> <target state="translated">Proměnná {0} {1}, která nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat {0} jako proměnnou s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_UninitializedNonNullableField_Title"> <source>Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.</source> <target state="translated">Pole, které nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat ho jako pole s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreadRecordParameter"> <source>Parameter '{0}' is unread. Did you forget to use it to initialize the property with that name?</source> <target state="translated">Parametr {0} se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem?</target> <note /> </trans-unit> <trans-unit id="WRN_UnreadRecordParameter_Title"> <source>Parameter is unread. Did you forget to use it to initialize the property with that name?</source> <target state="translated">Parametr se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem?</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolation"> <source>Use of unassigned local variable '{0}'</source> <target state="translated">Použila se nepřiřazená lokální proměnná {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationField"> <source>Use of possibly unassigned field '{0}'</source> <target state="translated">Použila se možná nepřiřazené pole {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationField_Title"> <source>Use of possibly unassigned field</source> <target state="translated">Použilo se pravděpodobně nepřiřazené pole</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationOut"> <source>Use of unassigned out parameter '{0}'</source> <target state="translated">Použil se nepřiřazený parametr out {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationOut_Title"> <source>Use of unassigned out parameter</source> <target state="translated">Použil se nepřiřazený parametr out</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationProperty"> <source>Use of possibly unassigned auto-implemented property '{0}'</source> <target state="translated">Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0}</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationProperty_Title"> <source>Use of possibly unassigned auto-implemented property</source> <target state="translated">Použily se pravděpodobně nepřiřazené automaticky implementované vlastnosti</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationThis"> <source>The 'this' object cannot be used before all of its fields have been assigned</source> <target state="translated">Objekt this se nedá použít, dokud se nepřiřadí všechna jeho pole.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationThis_Title"> <source>The 'this' object cannot be used in a constructor before all of its fields have been assigned</source> <target state="translated">Objekt this se v konstruktoru nedá použít, dokud se nepřiřadí všechna jeho pole</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolation_Title"> <source>Use of unassigned local variable</source> <target state="translated">Použila se nepřiřazená lokální proměnná</target> <note /> </trans-unit> <trans-unit id="XML_InvalidToken"> <source>The character(s) '{0}' cannot be used at this location.</source> <target state="translated">Znaky {0} se na tomto místě nedají použít.</target> <note /> </trans-unit> <trans-unit id="XML_IncorrectComment"> <source>Incorrect syntax was used in a comment.</source> <target state="translated">V komentáři se používá nesprávná syntaxe.</target> <note /> </trans-unit> <trans-unit id="XML_InvalidCharEntity"> <source>An invalid character was found inside an entity reference.</source> <target state="translated">Uvnitř odkazu na entitu se našel neplatný znak.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedEndOfTag"> <source>Expected '&gt;' or '/&gt;' to close tag '{0}'.</source> <target state="translated">Očekával se řetězec &gt; nebo /&gt; uzavírající značku {0}.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedIdentifier"> <source>An identifier was expected.</source> <target state="translated">Očekával se identifikátor.</target> <note /> </trans-unit> <trans-unit id="XML_InvalidUnicodeChar"> <source>Invalid unicode character.</source> <target state="translated">Neplatný znak unicode</target> <note /> </trans-unit> <trans-unit id="XML_InvalidWhitespace"> <source>Whitespace is not allowed at this location.</source> <target state="translated">Prázdný znak není v tomto místě povolený.</target> <note /> </trans-unit> <trans-unit id="XML_LessThanInAttributeValue"> <source>The character '&lt;' cannot be used in an attribute value.</source> <target state="translated">Znak &lt; se nedá použít v hodnotě atributu.</target> <note /> </trans-unit> <trans-unit id="XML_MissingEqualsAttribute"> <source>Missing equals sign between attribute and attribute value.</source> <target state="translated">Mezi atributem a jeho hodnotou chybí znaménko rovná se.</target> <note /> </trans-unit> <trans-unit id="XML_RefUndefinedEntity_1"> <source>Reference to undefined entity '{0}'.</source> <target state="translated">Odkaz na nedefinovanou entitu {0}</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNoStartQuote"> <source>A string literal was expected, but no opening quotation mark was found.</source> <target state="translated">Očekával se řetězcový literál, ale nenašly se úvodní uvozovky.</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNoEndQuote"> <source>Missing closing quotation mark for string literal.</source> <target state="translated">U řetězcového literálu chybí koncové uvozovky.</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNonAsciiQuote"> <source>Non-ASCII quotations marks may not be used around string literals.</source> <target state="translated">U řetězcových literálů se nesmí používat jiné uvozovky než ASCII.</target> <note /> </trans-unit> <trans-unit id="XML_EndTagNotExpected"> <source>End tag was not expected at this location.</source> <target state="translated">Na tomto místě se neočekávala koncová značka.</target> <note /> </trans-unit> <trans-unit id="XML_ElementTypeMatch"> <source>End tag '{0}' does not match the start tag '{1}'.</source> <target state="translated">Koncová značka {0} neodpovídá počáteční značce {1}.</target> <note /> </trans-unit> <trans-unit id="XML_EndTagExpected"> <source>Expected an end tag for element '{0}'.</source> <target state="translated">Očekávala se koncová značka pro element {0}.</target> <note /> </trans-unit> <trans-unit id="XML_WhitespaceMissing"> <source>Required white space was missing.</source> <target state="translated">Chybí požadovaná mezera.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedEndOfXml"> <source>Unexpected character at this location.</source> <target state="translated">Neočekávaný znak na tomto místě</target> <note /> </trans-unit> <trans-unit id="XML_CDataEndTagNotAllowed"> <source>The literal string ']]&gt;' is not allowed in element content.</source> <target state="translated">V obsahu elementu není povolený řetězec literálu ]]&gt;.</target> <note /> </trans-unit> <trans-unit id="XML_DuplicateAttribute"> <source>Duplicate '{0}' attribute</source> <target state="translated">Duplicitní atribut {0}</target> <note /> </trans-unit> <trans-unit id="ERR_NoMetadataFile"> <source>Metadata file '{0}' could not be found</source> <target state="translated">Soubor metadat {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataReferencesNotSupported"> <source>Metadata references are not supported.</source> <target state="translated">Odkazy v metadatech se nepodporují.</target> <note /> </trans-unit> <trans-unit id="FTL_MetadataCantOpenFile"> <source>Metadata file '{0}' could not be opened -- {1}</source> <target state="translated">Soubor metadat {0} nešel otevřít -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeDef"> <source>The type '{0}' is defined in an assembly that is not referenced. You must add a reference to assembly '{1}'.</source> <target state="translated">Typ {0} je definovaný jako sestavení, na které se neodkazuje. Je nutné přidat odkaz na sestavení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeDefFromModule"> <source>The type '{0}' is defined in a module that has not been added. You must add the module '{1}'.</source> <target state="translated">Typ {0} je definovaný v modulu, který jste nepřidali. Musíte přidat modul {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_OutputWriteFailed"> <source>Could not write to output file '{0}' -- '{1}'</source> <target state="translated">Do výstupního souboru {0} nejde zapisovat -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEntryPoints"> <source>Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.</source> <target state="translated">Program má definovaný víc než jeden vstupní bod. V kompilaci použijte /main určující typ, který vstupní bod obsahuje.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinaryOps"> <source>Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'</source> <target state="translated">Operátor {0} nejde použít na operandy typu {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_IntDivByZero"> <source>Division by constant zero</source> <target state="translated">Dělení nulovou konstantou</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexLHS"> <source>Cannot apply indexing with [] to an expression of type '{0}'</source> <target state="translated">Ve výrazu typu {0} nejde použít indexování pomocí hranatých závorek ([]).</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexCount"> <source>Wrong number of indices inside []; expected {0}</source> <target state="translated">Špatné číslo indexu uvnitř []; očekává se {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnaryOp"> <source>Operator '{0}' cannot be applied to operand of type '{1}'</source> <target state="translated">Operátor {0} nejde použít na operand typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisInStaticMeth"> <source>Keyword 'this' is not valid in a static property, static method, or static field initializer</source> <target state="translated">Klíčové slovo this není platné ve statické vlastnosti, ve statické metodě ani ve statickém inicializátoru pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisInBadContext"> <source>Keyword 'this' is not available in the current context</source> <target state="translated">Klíčové slovo this není v aktuálním kontextu k dispozici.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidMainSig"> <source>'{0}' has the wrong signature to be an entry point</source> <target state="translated">{0} nemá správný podpis, takže nemůže být vstupním bodem.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidMainSig_Title"> <source>Method has the wrong signature to be an entry point</source> <target state="translated">Metoda nemá správný podpis, takže nemůže být vstupním bodem.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConv"> <source>Cannot implicitly convert type '{0}' to '{1}'</source> <target state="translated">Typ {0} nejde implicitně převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitConv"> <source>Cannot convert type '{0}' to '{1}'</source> <target state="translated">Typ {0} nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstOutOfRange"> <source>Constant value '{0}' cannot be converted to a '{1}'</source> <target state="translated">Konstantní hodnotu {0} nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOps"> <source>Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'</source> <target state="translated">Operátor {0} je nejednoznačný na operandech typu {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigUnaryOp"> <source>Operator '{0}' is ambiguous on an operand of type '{1}'</source> <target state="translated">Operátor {0} je nejednoznačný na operandu typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_InAttrOnOutParam"> <source>An out parameter cannot have the In attribute</source> <target state="translated">Parametr out nemůže obsahovat atribut In.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueCantBeNull"> <source>Cannot convert null to '{0}' because it is a non-nullable value type</source> <target state="translated">Hodnotu null nejde převést na typ {0}, protože se jedná o typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitBuiltinConv"> <source>Cannot convert type '{0}' to '{1}' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion</source> <target state="translated">Typ {0} nejde převést na {1} prostřednictvím převodu odkazu, převodu zabalení, převodu rozbalení, převodu obálky nebo převodu s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="FTL_DebugEmitFailure"> <source>Unexpected error writing debug information -- '{0}'</source> <target state="translated">Neočekávaná chyba při zápisu ladicích informací -- {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisReturnType"> <source>Inconsistent accessibility: return type '{1}' is less accessible than method '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než metoda {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisParamType"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než metoda {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisFieldType"> <source>Inconsistent accessibility: field type '{1}' is less accessible than field '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ pole {1} je míň dostupný než pole {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisPropertyType"> <source>Inconsistent accessibility: property type '{1}' is less accessible than property '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vlastnosti {1} je míň dostupný než vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisIndexerReturn"> <source>Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty indexeru {1} je méně dostupný než indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisIndexerParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisOpReturn"> <source>Inconsistent accessibility: return type '{1}' is less accessible than operator '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než operátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisOpParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than operator '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než operátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisDelegateReturn"> <source>Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než delegát {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisDelegateParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než delegát {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBaseClass"> <source>Inconsistent accessibility: base class '{1}' is less accessible than class '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Základní třída {1} je míň dostupná než třída {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBaseInterface"> <source>Inconsistent accessibility: base interface '{1}' is less accessible than interface '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Základní rozhraní {1} je míň dostupné než rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_EventNeedsBothAccessors"> <source>'{0}': event property must have both add and remove accessors</source> <target state="translated">{0}: Vlastnost události musí obsahovat přistupující objekty add i remove.</target> <note /> </trans-unit> <trans-unit id="ERR_EventNotDelegate"> <source>'{0}': event must be of a delegate type</source> <target state="translated">{0}: Událost musí být typu delegát.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedEvent"> <source>The event '{0}' is never used</source> <target state="translated">Událost {0} se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedEvent_Title"> <source>Event is never used</source> <target state="translated">Událost se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceEventInitializer"> <source>'{0}': instance event in interface cannot have initializer</source> <target state="translated">{0}: Událost instance v rozhraní nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventUsage"> <source>The event '{0}' can only appear on the left hand side of += or -= (except when used from within the type '{1}')</source> <target state="translated">Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -= (s výjimkou případu, kdy se používá z typu {1}).</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitEventFieldImpl"> <source>An explicit interface implementation of an event must use event accessor syntax</source> <target state="translated">Explicitní implementace rozhraní události musí používat syntaxi přistupujícího objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonEvent"> <source>'{0}': cannot override; '{1}' is not an event</source> <target state="translated">{0}: Nejde přepsat; {1} není událost.</target> <note /> </trans-unit> <trans-unit id="ERR_AddRemoveMustHaveBody"> <source>An add or remove accessor must have a body</source> <target state="translated">Přistupující objekty add a remove musí mít tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractEventInitializer"> <source>'{0}': abstract event cannot have initializer</source> <target state="translated">{0}: Abstraktní událost nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedAssemblyName"> <source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source> <target state="translated">Název sestavení {0} je rezervovaný a nedá se použít jako odkaz v interaktivní relaci.</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedEnumerator"> <source>The enumerator name '{0}' is reserved and cannot be used</source> <target state="translated">Název čítače výčtu {0} je rezervovaný a nedá se použít.</target> <note /> </trans-unit> <trans-unit id="ERR_AsMustHaveReferenceType"> <source>The as operator must be used with a reference type or nullable type ('{0}' is a non-nullable value type)</source> <target state="translated">Operátor as je třeba použít s typem odkazu nebo s typem připouštějícím hodnotu null ({0} je typ hodnoty, který nepřipouští hodnotu null).</target> <note /> </trans-unit> <trans-unit id="WRN_LowercaseEllSuffix"> <source>The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity</source> <target state="translated">Přípona l je snadno zaměnitelná s číslicí 1. V zájmu větší srozumitelnosti použijte písmeno L.</target> <note /> </trans-unit> <trans-unit id="WRN_LowercaseEllSuffix_Title"> <source>The 'l' suffix is easily confused with the digit '1'</source> <target state="translated">Přípona l je snadno zaměnitelná s číslicí 1.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventUsageNoField"> <source>The event '{0}' can only appear on the left hand side of += or -=</source> <target state="translated">Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -=.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintOnlyAllowedOnGenericDecl"> <source>Constraints are not allowed on non-generic declarations</source> <target state="translated">U neobecných deklarací nejsou povolená omezení.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMustBeIdentifier"> <source>Type parameter declaration must be an identifier not a type</source> <target state="translated">Deklarace parametru typů musí být identifikátor, ne typ.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberReserved"> <source>Type '{1}' already reserves a member called '{0}' with the same parameter types</source> <target state="translated">Typ {1} už rezervuje člen s názvem {0} se stejnými typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParamName"> <source>The parameter name '{0}' is a duplicate</source> <target state="translated">Název parametru {0} je duplicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNameInNS"> <source>The namespace '{1}' already contains a definition for '{0}'</source> <target state="translated">Obor názvů {1} už obsahuje definici pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNameInClass"> <source>The type '{0}' already contains a definition for '{1}'</source> <target state="translated">Typ {0} už obsahuje definici pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotInContext"> <source>The name '{0}' does not exist in the current context</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje.</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotInContextPossibleMissingReference"> <source>The name '{0}' does not exist in the current context (are you missing a reference to assembly '{1}'?)</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje. (Nechybí odkaz na sestavení {1}?)</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigContext"> <source>'{0}' is an ambiguous reference between '{1}' and '{2}'</source> <target state="translated">{0} je nejednoznačný odkaz mezi {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateUsing"> <source>The using directive for '{0}' appeared previously in this namespace</source> <target state="translated">Direktiva using pro {0} se objevila už dřív v tomto oboru názvů.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateUsing_Title"> <source>Using directive appeared previously in this namespace</source> <target state="translated">Direktiva Using se už v tomto oboru názvů objevila dříve.</target> <note /> </trans-unit> <trans-unit id="ERR_BadMemberFlag"> <source>The modifier '{0}' is not valid for this item</source> <target state="translated">Modifikátor {0} není pro tuto položku platný.</target> <note /> </trans-unit> <trans-unit id="ERR_BadMemberProtection"> <source>More than one protection modifier</source> <target state="translated">Víc než jeden modifikátor ochrany</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired"> <source>'{0}' hides inherited member '{1}'. Use the new keyword if hiding was intended.</source> <target state="translated">{0} skryje zděděný člen {1}. Pokud je skrytí úmyslné, použijte klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired_Title"> <source>Member hides inherited member; missing new keyword</source> <target state="translated">Člen skrývá zděděný člen. Chybí klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired_Description"> <source>A variable was declared with the same name as a variable in a base type. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration.</source> <target state="translated">Proměnná se deklarovala se stejným názvem jako proměnná v základním typu. Klíčové slovo new se ale nepoužilo. Toto varování vás informuje, že byste měli použít new; proměnná je deklarovaná, jako by se v deklaraci používalo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewNotRequired"> <source>The member '{0}' does not hide an accessible member. The new keyword is not required.</source> <target state="translated">Člen {0} neskrývá přístupný člen. Klíčové slovo new se nevyžaduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NewNotRequired_Title"> <source>Member does not hide an inherited member; new keyword is not required</source> <target state="translated">Člen neskrývá zděděný člen. Klíčové slovo new se nevyžaduje.</target> <note /> </trans-unit> <trans-unit id="ERR_CircConstValue"> <source>The evaluation of the constant value for '{0}' involves a circular definition</source> <target state="translated">Vyhodnocení konstantní hodnoty pro {0} zahrnuje cyklickou definici.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberAlreadyExists"> <source>Type '{1}' already defines a member called '{0}' with the same parameter types</source> <target state="translated">Typ {1} už definuje člen s názvem {0} se stejnými typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticNotVirtual"> <source>A static member cannot be marked as '{0}'</source> <target state="needs-review-translation">Statický člen {0} nemůže být označený klíčovými slovy override, virtual nebo abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotNew"> <source>A member '{0}' marked as override cannot be marked as new or virtual</source> <target state="translated">Člen {0} označený jako override nejde označit jako new nebo virtual.</target> <note /> </trans-unit> <trans-unit id="WRN_NewOrOverrideExpected"> <source>'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.</source> <target state="translated">'Člen {0} skryje zděděný člen {1}. Pokud má aktuální člen tuto implementaci přepsat, přidejte klíčové slovo override. Jinak přidejte klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewOrOverrideExpected_Title"> <source>Member hides inherited member; missing override keyword</source> <target state="translated">Člen skrývá zděděný člen. Chybí klíčové slovo override.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotExpected"> <source>'{0}': no suitable method found to override</source> <target state="translated">{0}: Nenašla se vhodná metoda k přepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceUnexpected"> <source>A namespace cannot directly contain members such as fields, methods or statements</source> <target state="needs-review-translation">Obor názvů nemůže přímo obsahovat členy, jako jsou pole a metody.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMember"> <source>'{0}' does not contain a definition for '{1}'</source> <target state="translated">{0} neobsahuje definici pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSKknown"> <source>'{0}' is a {1} but is used like a {2}</source> <target state="translated">{0} je {1}, ale používá se jako {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSKunknown"> <source>'{0}' is a {1}, which is not valid in the given context</source> <target state="translated">{0} je {1}, což není platné v daném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectRequired"> <source>An object reference is required for the non-static field, method, or property '{0}'</source> <target state="translated">Pro nestatické pole, metodu nebo vlastnost {0} se vyžaduje odkaz na objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigCall"> <source>The call is ambiguous between the following methods or properties: '{0}' and '{1}'</source> <target state="translated">Volání je nejednoznačné mezi následujícími metodami nebo vlastnostmi: {0} a {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAccess"> <source>'{0}' is inaccessible due to its protection level</source> <target state="translated">'Typ {0} je vzhledem k úrovni ochrany nepřístupný.</target> <note /> </trans-unit> <trans-unit id="ERR_MethDelegateMismatch"> <source>No overload for '{0}' matches delegate '{1}'</source> <target state="translated">Žádná přetížená metoda {0} neodpovídá delegátovi {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RetObjectRequired"> <source>An object of a type convertible to '{0}' is required</source> <target state="translated">Vyžaduje se objekt typu, který se dá převést na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RetNoObjectRequired"> <source>Since '{0}' returns void, a return keyword must not be followed by an object expression</source> <target state="translated">Protože {0} vrací void, nesmí za klíčovým slovem return následovat výraz objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalDuplicate"> <source>A local variable or function named '{0}' is already defined in this scope</source> <target state="translated">Lokální proměnná nebo funkce s názvem {0} je už v tomto oboru definovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgLvalueExpected"> <source>The left-hand side of an assignment must be a variable, property or indexer</source> <target state="translated">Levou stranou přiřazení musí být proměnná, vlastnost nebo indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstParam"> <source>'{0}': a static constructor must be parameterless</source> <target state="translated">{0}: Statický konstruktor musí být bez parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_NotConstantExpression"> <source>The expression being assigned to '{0}' must be constant</source> <target state="translated">Výraz přiřazovaný proměnné {0} musí být konstantou.</target> <note /> </trans-unit> <trans-unit id="ERR_NotNullConstRefField"> <source>'{0}' is of type '{1}'. A const field of a reference type other than string can only be initialized with null.</source> <target state="translated">{0} je typu {1}. Pole const s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalIllegallyOverrides"> <source>A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter</source> <target state="translated">Místní proměnná nebo parametr s názvem {0} se nedá deklarovat v tomto oboru, protože se tento název používá v uzavírajícím místním oboru pro definování místní proměnné nebo parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUsingNamespace"> <source>A 'using namespace' directive can only be applied to namespaces; '{0}' is a type not a namespace. Consider a 'using static' directive instead</source> <target state="translated">Direktivu using namespace jde uplatnit jenom u oborů názvů; {0} je typ, ne obor názvů. Zkuste radši použít direktivu using static.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUsingType"> <source>A 'using static' directive can only be applied to types; '{0}' is a namespace not a type. Consider a 'using namespace' directive instead</source> <target state="translated">Direktiva using static se dá použít jenom u typů; {0} je obor názvů, ne typ. Zkuste radši použít direktivu using namespace.</target> <note /> </trans-unit> <trans-unit id="ERR_NoAliasHere"> <source>A 'using static' directive cannot be used to declare an alias</source> <target state="translated">Direktiva using static se nedá použít k deklarování aliasu.</target> <note /> </trans-unit> <trans-unit id="ERR_NoBreakOrCont"> <source>No enclosing loop out of which to break or continue</source> <target state="translated">Příkazy break a continue nejsou uvedené ve smyčce.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLabel"> <source>The label '{0}' is a duplicate</source> <target state="translated">Návěstí {0} je duplicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstructors"> <source>The type '{0}' has no constructors defined</source> <target state="translated">Pro typ {0} nejsou definované žádné konstruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNewAbstract"> <source>Cannot create an instance of the abstract type or interface '{0}'</source> <target state="translated">Nejde vytvořit instanci abstraktního typu nebo rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstValueRequired"> <source>A const field requires a value to be provided</source> <target state="translated">Pole const vyžaduje zadání hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_CircularBase"> <source>Circular base type dependency involving '{0}' and '{1}'</source> <target state="translated">Prvky {0} a {1} jsou součástí cyklické závislosti základního typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateConstructor"> <source>The delegate '{0}' does not have a valid constructor</source> <target state="translated">Delegát {0} nemá platný konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodNameExpected"> <source>Method name expected</source> <target state="translated">Očekává se název metody.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantExpected"> <source>A constant value is expected</source> <target state="translated">Očekává se konstantní hodnota.</target> <note /> </trans-unit> <trans-unit id="ERR_V6SwitchGoverningTypeValueExpected"> <source>A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier.</source> <target state="translated">Výraz switch nebo popisek větve musí být bool, char, string, integral, enum nebo odpovídající typ s možnou hodnotou null v jazyce C# 6 nebo starším.</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralTypeValueExpected"> <source>A value of an integral type expected</source> <target state="translated">Očekává se hodnota integrálního typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateCaseLabel"> <source>The switch statement contains multiple cases with the label value '{0}'</source> <target state="translated">Příkaz switch obsahuje víc případů s hodnotou návěstí {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidGotoCase"> <source>A goto case is only valid inside a switch statement</source> <target state="translated">Příkaz goto case je platný jenom uvnitř příkazu switch.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyLacksGet"> <source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože neobsahuje přistupující objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExceptionType"> <source>The type caught or thrown must be derived from System.Exception</source> <target state="translated">Zachycený nebo vyvolaný typ musí být odvozený od třídy System.Exception.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyThrow"> <source>A throw statement with no arguments is not allowed outside of a catch clause</source> <target state="translated">Příkaz throw bez argumentů není povolený vně klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFinallyLeave"> <source>Control cannot leave the body of a finally clause</source> <target state="translated">Řízení nemůže opustit tělo klauzule finally.</target> <note /> </trans-unit> <trans-unit id="ERR_LabelShadow"> <source>The label '{0}' shadows another label by the same name in a contained scope</source> <target state="translated">Návěstí {0} stíní v obsaženém oboru jiné návěstí se stejným názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_LabelNotFound"> <source>No such label '{0}' within the scope of the goto statement</source> <target state="translated">V rozsahu příkazu goto není žádné takové návěstí {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnreachableCatch"> <source>A previous catch clause already catches all exceptions of this or of a super type ('{0}')</source> <target state="translated">Předchozí klauzule catch už zachytává všechny výjimky vyvolávané tímto typem nebo nadtypem ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantTrue"> <source>Filter expression is a constant 'true', consider removing the filter</source> <target state="translated">Výraz filtru je konstantní hodnota true. Zvažte odebrání filtru.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantTrue_Title"> <source>Filter expression is a constant 'true'</source> <target state="translated">Výraz filtru je konstantní hodnota true.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnExpected"> <source>'{0}': not all code paths return a value</source> <target state="translated">{0}: Ne všechny cesty kódu vrací hodnotu.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode_Title"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchFallThrough"> <source>Control cannot fall through from one case label ('{0}') to another</source> <target state="translated">Řízení se nedá předat z jednoho návěstí příkazu case ({0}) do jiného.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLabel"> <source>This label has not been referenced</source> <target state="translated">Na tuto jmenovku se neodkazuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLabel_Title"> <source>This label has not been referenced</source> <target state="translated">Na tuto jmenovku se neodkazuje.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolation"> <source>Use of unassigned local variable '{0}'</source> <target state="translated">Použila se nepřiřazená lokální proměnná {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVar"> <source>The variable '{0}' is declared but never used</source> <target state="translated">Proměnná {0} je deklarovaná, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVar_Title"> <source>Variable is declared but never used</source> <target state="translated">Proměnná je deklarovaná, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedField"> <source>The field '{0}' is never used</source> <target state="translated">Pole {0} se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedField_Title"> <source>Field is never used</source> <target state="translated">Pole se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationField"> <source>Use of possibly unassigned field '{0}'</source> <target state="translated">Použila se možná nepřiřazené pole {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationProperty"> <source>Use of possibly unassigned auto-implemented property '{0}'</source> <target state="translated">Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnassignedThis"> <source>Field '{0}' must be fully assigned before control is returned to the caller</source> <target state="translated">Před předáním řízení volající proceduře musí být pole {0} plně přiřazené.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigQM"> <source>Type of conditional expression cannot be determined because '{0}' and '{1}' implicitly convert to one another</source> <target state="translated">Typ podmíněného výrazu nejde určit, protože {0} a {1} se implicitně převádějí jeden na druhého.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidQM"> <source>Type of conditional expression cannot be determined because there is no implicit conversion between '{0}' and '{1}'</source> <target state="translated">Nejde zjistit typ podmíněného výrazu, protože mezi typy {0} a {1} nedochází k implicitnímu převodu</target> <note /> </trans-unit> <trans-unit id="ERR_NoBaseClass"> <source>A base class is required for a 'base' reference</source> <target state="translated">Pro odkaz base se vyžaduje základní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseIllegal"> <source>Use of keyword 'base' is not valid in this context</source> <target state="translated">Použití klíčového slova base není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectProhibited"> <source>Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead</source> <target state="translated">K členovi {0} nejde přistupovat pomocí odkazu na instanci. Namísto toho použijte kvalifikaci pomocí názvu typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamUnassigned"> <source>The out parameter '{0}' must be assigned to before control leaves the current method</source> <target state="translated">Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidArray"> <source>Invalid rank specifier: expected ',' or ']'</source> <target state="translated">Specifikátor rozsahu je neplatný. Očekávala se čárka (,) nebo pravá hranatá závorka ].</target> <note /> </trans-unit> <trans-unit id="ERR_ExternHasBody"> <source>'{0}' cannot be extern and declare a body</source> <target state="translated">{0} nemůže být extern a deklarovat tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternHasConstructorInitializer"> <source>'{0}' cannot be extern and have a constructor initializer</source> <target state="translated">{0} nemůže být extern a mít inicializátor konstruktoru.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAndExtern"> <source>'{0}' cannot be both extern and abstract</source> <target state="translated">{0} nemůže být extern i abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeParamType"> <source>Attribute constructor parameter '{0}' has type '{1}', which is not a valid attribute parameter type</source> <target state="translated">Parametr {0} konstruktoru atributu má typ {1}, což není platný typ pro parametr atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeArgument"> <source>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type</source> <target state="translated">Argumentem atributu musí být konstantní výraz, výraz typeof nebo výraz vytvoření pole s typem parametru atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeParamDefaultArgument"> <source>Attribute constructor parameter '{0}' is optional, but no default parameter value was specified.</source> <target state="translated">Parametr {0} konstruktoru atributu je nepovinný, ale nebyla zadaná žádná výchozí hodnota parametru.</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysTrue"> <source>The given expression is always of the provided ('{0}') type</source> <target state="translated">Tento výraz je vždy zadaného typu ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysTrue_Title"> <source>'is' expression's given expression is always of the provided type</source> <target state="translated">'Daný výraz is je vždycky zadaného typu.</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysFalse"> <source>The given expression is never of the provided ('{0}') type</source> <target state="translated">Tento výraz nikdy není zadaného typu ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysFalse_Title"> <source>'is' expression's given expression is never of the provided type</source> <target state="translated">'Daný výraz is není nikdy zadaného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_LockNeedsReference"> <source>'{0}' is not a reference type as required by the lock statement</source> <target state="translated">{0} není typu odkaz, jak vyžaduje příkaz lock</target> <note /> </trans-unit> <trans-unit id="ERR_NullNotValid"> <source>Use of null is not valid in this context</source> <target state="translated">Použití hodnoty NULL není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultLiteralNotValid"> <source>Use of default literal is not valid in this context</source> <target state="translated">Použití výchozího literálu není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationThis"> <source>The 'this' object cannot be used before all of its fields have been assigned</source> <target state="translated">Objekt this se nedá použít, dokud se nepřiřadí všechna jeho pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ArgsInvalid"> <source>The __arglist construct is valid only within a variable argument method</source> <target state="translated">Konstrukce __arglist je platná jenom v rámci metody s proměnnými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_PtrExpected"> <source>The * or -&gt; operator must be applied to a pointer</source> <target state="translated">Operátor * nebo -&gt; musí být použitý u ukazatele.</target> <note /> </trans-unit> <trans-unit id="ERR_PtrIndexSingle"> <source>A pointer must be indexed by only one value</source> <target state="translated">Ukazatel může být indexován jenom jednou hodnotou.</target> <note /> </trans-unit> <trans-unit id="WRN_ByRefNonAgileField"> <source>Using '{0}' as a ref or out value or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class</source> <target state="translated">Použití prvku {0} jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit výjimku při běhu, protože se jedná o pole třídy marshal-by-reference.</target> <note /> </trans-unit> <trans-unit id="WRN_ByRefNonAgileField_Title"> <source>Using a field of a marshal-by-reference class as a ref or out value or taking its address may cause a runtime exception</source> <target state="translated">Použití pole třídy marshal-by-reference jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit běhovou výjimku.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyStatic"> <source>A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)</source> <target state="translated">Do statického pole určeného jen pro čtení nejde přiřazovat (kromě případu, kdy se nachází uvnitř statického konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyStatic"> <source>A static readonly field cannot be used as a ref or out value (except in a static constructor)</source> <target state="translated">Statické pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř statického konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyProp"> <source>Property or indexer '{0}' cannot be assigned to -- it is read only</source> <target state="translated">Vlastnost nebo indexer {0} nejde přiřadit – je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalStatement"> <source>Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement</source> <target state="translated">Jako příkaz jde použít jenom objektové výrazy přiřazení, volání, zvýšení nebo snížení hodnoty nebo výrazy obsahující operátor new.</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetEnumerator"> <source>foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNext' method and public 'Current' property</source> <target state="translated">Příkaz foreach vyžaduje, aby typ vracených hodnot {0} pro {1} měl vhodnou veřejnou metodu MoveNext a veřejnou vlastnost Current.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyLocals"> <source>Only 65534 locals, including those generated by the compiler, are allowed</source> <target state="translated">Je povolených jenom 65 534 lokálních proměnných, včetně těch, které generuje kompilátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractBaseCall"> <source>Cannot call an abstract base member: '{0}'</source> <target state="translated">Nejde volat abstraktní základní člen: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefProperty"> <source>A property or indexer may not be passed as an out or ref parameter</source> <target state="translated">Vlastnost nebo indexer nejde předat jako parametr ref nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_ManagedAddr"> <source>Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')</source> <target state="translated">Nejde převzít adresu proměnné spravovaného typu ({0}), získat její velikost nebo deklarovat ukazatel na ni.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFixedInitType"> <source>The type of a local declared in a fixed statement must be a pointer type</source> <target state="translated">Lokální proměnná deklarovaná v příkazu fixed musí být typu ukazatel.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedMustInit"> <source>You must provide an initializer in a fixed or using statement declaration</source> <target state="translated">V deklaracích příkazů fixed a using je nutné zadat inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAddrOp"> <source>Cannot take the address of the given expression</source> <target state="translated">Nejde převzít adresu daného výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNeeded"> <source>You can only take the address of an unfixed expression inside of a fixed statement initializer</source> <target state="translated">Adresu volného výrazu jde převzít jenom uvnitř inicializátoru příkazu fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNotNeeded"> <source>You cannot use the fixed statement to take the address of an already fixed expression</source> <target state="translated">K převzetí adresy výrazu, který je už nastavený jako pevný, nejde použít příkaz fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeNeeded"> <source>Pointers and fixed size buffers may only be used in an unsafe context</source> <target state="translated">Ukazatele a vyrovnávací paměti pevné velikosti jde použít jenom v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_OpTFRetType"> <source>The return type of operator True or False must be bool</source> <target state="translated">Vrácená hodnota operátorů True a False musí být typu bool.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorNeedsMatch"> <source>The operator '{0}' requires a matching operator '{1}' to also be defined</source> <target state="translated">Operátor {0} vyžaduje, aby byl definovaný i odpovídající operátor {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBoolOp"> <source>In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type and parameter types</source> <target state="translated">Pokud má být uživatelem definovaný logický operátor ({0}) použitelný jako operátor zkráceného vyhodnocení, musí vracet hodnotu stejného typu a mít stejné typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MustHaveOpTF"> <source>In order for '{0}' to be applicable as a short circuit operator, its declaring type '{1}' must define operator true and operator false</source> <target state="translated">Aby byl {0} použitelný jako operátor zkráceného vyhodnocení, musí jeho deklarující typ {1} definovat operátor true a operátor false.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVarAssg"> <source>The variable '{0}' is assigned but its value is never used</source> <target state="translated">Proměnná {0} má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVarAssg_Title"> <source>Variable is assigned but its value is never used</source> <target state="translated">Proměnná má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_CheckedOverflow"> <source>The operation overflows at compile time in checked mode</source> <target state="translated">Během kompilace v režimu kontroly došlo k přetečení.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstOutOfRangeChecked"> <source>Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnotu {0} nejde převést na typ {1} (k přepsání jde použít syntaxi unchecked).</target> <note /> </trans-unit> <trans-unit id="ERR_BadVarargs"> <source>A method with vararg cannot be generic, be in a generic type, or have a params parameter</source> <target state="translated">Metoda s parametrem vararg nemůže být obecná, být obecného typu nebo mít pole parametr params.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsMustBeArray"> <source>The params parameter must be a single dimensional array</source> <target state="translated">Parametr params musí být jednorozměrné pole.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalArglist"> <source>An __arglist expression may only appear inside of a call or new expression</source> <target state="translated">Výraz __arglist může být jedině uvnitř volání nebo výrazu new.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalUnsafe"> <source>Unsafe code may only appear if compiling with /unsafe</source> <target state="translated">Nebezpečný kód může vzniknout jenom při kompilaci s přepínačem /unsafe.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigMember"> <source>Ambiguity between '{0}' and '{1}'</source> <target state="translated">Došlo k nejednoznačnosti mezi metodami nebo vlastnostmi {0} a {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadForeachDecl"> <source>Type and identifier are both required in a foreach statement</source> <target state="translated">V příkazu foreach se vyžaduje typ i identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsLast"> <source>A params parameter must be the last parameter in a formal parameter list</source> <target state="translated">Parametr params musí být posledním parametrem v seznamu formálních parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_SizeofUnsafe"> <source>'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context</source> <target state="translated">{0} nemá předdefinovanou velikost. Operátor sizeof jde proto použít jenom v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInNS"> <source>The type or namespace name '{0}' does not exist in the namespace '{1}' (are you missing an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} neexistuje v oboru názvů {1}. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_FieldInitRefNonstatic"> <source>A field initializer cannot reference the non-static field, method, or property '{0}'</source> <target state="translated">Inicializátor pole nemůže odkazovat na nestatické pole, metodu nebo vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedNonOverride"> <source>'{0}' cannot be sealed because it is not an override</source> <target state="translated">{0} nejde zapečetit, protože to není přepis.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideSealed"> <source>'{0}': cannot override inherited member '{1}' because it is sealed</source> <target state="translated">{0}: Nejde přepsat zděděný člen {1}, protože je zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidError"> <source>The operation in question is undefined on void pointers</source> <target state="translated">Příslušná operace není definovaná pro ukazatele typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnOverride"> <source>The Conditional attribute is not valid on '{0}' because it is an override method</source> <target state="translated">Atribut Conditional není pro {0} platný, protože je to metoda override.</target> <note /> </trans-unit> <trans-unit id="ERR_PointerInAsOrIs"> <source>Neither 'is' nor 'as' is valid on pointer types</source> <target state="translated">Klíčová slova is a as nejsou platná pro ukazatele.</target> <note /> </trans-unit> <trans-unit id="ERR_CallingFinalizeDeprecated"> <source>Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.</source> <target state="translated">Destruktory a metodu object.Finalize nejde volat přímo. Zvažte možnost volání metody IDisposable.Dispose, pokud je k dispozici.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleTypeNameNotFound"> <source>The type or namespace name '{0}' could not be found (are you missing a using directive or an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} se nenašel. (Nechybí direktiva using nebo odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeStackAllocSize"> <source>Cannot use a negative size with stackalloc</source> <target state="translated">Ve výrazu stackalloc nejde použít zápornou velikost.</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeArraySize"> <source>Cannot create an array with a negative size</source> <target state="translated">Nejde vytvořit pole se zápornou velikostí.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideFinalizeDeprecated"> <source>Do not override object.Finalize. Instead, provide a destructor.</source> <target state="translated">Nepřepisujte metodu object.Finalize. Raději použijte destruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_CallingBaseFinalizeDeprecated"> <source>Do not directly call your base type Finalize method. It is called automatically from your destructor.</source> <target state="translated">Nevolejte přímo metodu Finalize základního typu. Tuto metodu volá automaticky destruktor.</target> <note /> </trans-unit> <trans-unit id="WRN_NegativeArrayIndex"> <source>Indexing an array with a negative index (array indices always start at zero)</source> <target state="translated">Došlo k indexování pole záporným indexem (indexy polí vždy začínají hodnotou 0).</target> <note /> </trans-unit> <trans-unit id="WRN_NegativeArrayIndex_Title"> <source>Indexing an array with a negative index</source> <target state="translated">Došlo k indexování pole záporným indexem.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareLeft"> <source>Possible unintended reference comparison; to get a value comparison, cast the left hand side to type '{0}'</source> <target state="translated">Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte levou stranu na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareLeft_Title"> <source>Possible unintended reference comparison; left hand side needs cast</source> <target state="translated">Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat levou stranu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareRight"> <source>Possible unintended reference comparison; to get a value comparison, cast the right hand side to type '{0}'</source> <target state="translated">Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte pravou stranu na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareRight_Title"> <source>Possible unintended reference comparison; right hand side needs cast</source> <target state="translated">Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat pravou stranu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCastInFixed"> <source>The right hand side of a fixed statement assignment may not be a cast expression</source> <target state="translated">Pravá strana přiřazení příkazu fixed nemůže být výrazem přetypování.</target> <note /> </trans-unit> <trans-unit id="ERR_StackallocInCatchFinally"> <source>stackalloc may not be used in a catch or finally block</source> <target state="translated">Výraz stackalloc nejde použít v bloku catch nebo finally.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsLast"> <source>An __arglist parameter must be the last parameter in a formal parameter list</source> <target state="translated">Parametr __arglist musí být posledním parametrem v seznamu formálních parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPartial"> <source>Missing partial modifier on declaration of type '{0}'; another partial declaration of this type exists</source> <target state="translated">Chybí částečný modifikátor deklarace typu {0}; existuje jiná částečná deklarace tohoto typu.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeKindConflict"> <source>Partial declarations of '{0}' must be all classes, all record classes, all structs, all record structs, or all interfaces</source> <target state="needs-review-translation">Částečné deklarace {0} musí být jen třídy, jen záznamy, jen struktury, nebo jen rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialModifierConflict"> <source>Partial declarations of '{0}' have conflicting accessibility modifiers</source> <target state="translated">Částečné deklarace {0} mají konfliktní modifikátory dostupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMultipleBases"> <source>Partial declarations of '{0}' must not specify different base classes</source> <target state="translated">Částečné deklarace {0} nesmí určovat různé základní třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongTypeParams"> <source>Partial declarations of '{0}' must have the same type parameter names in the same order</source> <target state="translated">Částečné deklarace {0} musí mít stejné názvy parametrů typů ve stejném pořadí.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongConstraints"> <source>Partial declarations of '{0}' have inconsistent constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace {0} mají nekonzistentní omezení parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConvCast"> <source>Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)</source> <target state="translated">Typ {0} nejde implicitně převést na typ {1}. Existuje explicitní převod. (Nechybí výraz přetypování?)</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMisplaced"> <source>The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.</source> <target state="translated">Modifikátor partial se může objevit jen bezprostředně před klíčovými slovy class, record, struct, interface nebo návratovým typem metody.</target> <note /> </trans-unit> <trans-unit id="ERR_ImportedCircularBase"> <source>Imported type '{0}' is invalid. It contains a circular base type dependency.</source> <target state="translated">Importovaný typ {0} je neplatný. Obsahuje cyklickou závislost základních typů.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationOut"> <source>Use of unassigned out parameter '{0}'</source> <target state="translated">Použil se nepřiřazený parametr out {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ArraySizeInDeclaration"> <source>Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)</source> <target state="translated">Velikost pole nejde určit v deklaraci proměnné (zkuste inicializaci pomocí výrazu new).</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleGetter"> <source>The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt get není dostupný.</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleSetter"> <source>The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt jet není dostupný.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPropertyAccessMod"> <source>The accessibility modifier of the '{0}' accessor must be more restrictive than the property or indexer '{1}'</source> <target state="translated">Modifikátor dostupnosti přistupujícího objektu {0} musí být více omezující než vlastnost nebo indexer {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyAccessMods"> <source>Cannot specify accessibility modifiers for both accessors of the property or indexer '{0}'</source> <target state="translated">Nejde zadat modifikátory dostupnosti pro přistupující objekty jak vlastnosti, tak i indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AccessModMissingAccessor"> <source>'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor</source> <target state="translated">{0}: Modifikátory přístupnosti u přistupujících objektů se můžou používat, jenom pokud vlastnost nebo indexeru má přistupující objekt get i set.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedInterfaceAccessor"> <source>'{0}' does not implement interface member '{1}'. '{2}' is not public.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} není veřejný.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternIsAmbiguous"> <source>'{0}' does not implement the '{1}' pattern. '{2}' is ambiguous with '{3}'.</source> <target state="translated">{0} neimplementuje vzorek {1}. {2} je nejednoznačný vzhledem k: {3}.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternIsAmbiguous_Title"> <source>Type does not implement the collection pattern; members are ambiguous</source> <target state="translated">Typ neimplementuje vzorek kolekce. Členové nejsou jednoznační.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternBadSignature"> <source>'{0}' does not implement the '{1}' pattern. '{2}' has the wrong signature.</source> <target state="translated">{0} neimplementuje vzorek {1}. {2} nemá správný podpis.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternBadSignature_Title"> <source>Type does not implement the collection pattern; member has the wrong signature</source> <target state="translated">Typ neimplementuje vzorek kolekce. Člen nemá správný podpis.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefNotEqualToThis"> <source>Friend access was granted by '{0}', but the public key of the output assembly ('{1}') does not match that specified by the InternalsVisibleTo attribute in the granting assembly.</source> <target state="translated">Sestavení {0} udělilo přístup typu Friend, ale veřejný klíč výstupního sestavení ({1}) neodpovídá klíči určenému atributem InternalsVisibleTo v udělujícím sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefSigningMismatch"> <source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source> <target state="translated">Sestavení {0} udělilo přístup typu Friend, ale stav podepsání silného názvu u výstupního sestavení neodpovídá stavu udělujícího sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_SequentialOnPartialClass"> <source>There is no defined ordering between fields in multiple declarations of partial struct '{0}'. To specify an ordering, all instance fields must be in the same declaration.</source> <target state="translated">Mezi poli více deklarací částečné třídy nebo struktury {0} není žádné definované řazení. Pokud chcete zadat řazení, musí být všechna pole instancí ve stejné deklaraci.</target> <note /> </trans-unit> <trans-unit id="WRN_SequentialOnPartialClass_Title"> <source>There is no defined ordering between fields in multiple declarations of partial struct</source> <target state="translated">Není nadefinované řazení mezi poli ve více deklaracích částečné struktury.</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstType"> <source>The type '{0}' cannot be declared const</source> <target state="translated">Typ {0} nemůže být deklarovaný jako const.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNewTyvar"> <source>Cannot create an instance of the variable type '{0}' because it does not have the new() constraint</source> <target state="translated">Nejde vytvořit instanci proměnné typu {0}, protože nemá omezení new().</target> <note /> </trans-unit> <trans-unit id="ERR_BadArity"> <source>Using the generic {1} '{0}' requires {2} type arguments</source> <target state="translated">Použití obecného prvku {1} {0} vyžaduje tento počet argumentů typů: {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgument"> <source>The type '{0}' may not be used as a type argument</source> <target state="translated">Typ {0} nejde použít jako argument typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeArgsNotAllowed"> <source>The {1} '{0}' cannot be used with type arguments</source> <target state="translated">{1} {0} nejde použít s argumenty typů.</target> <note /> </trans-unit> <trans-unit id="ERR_HasNoTypeVars"> <source>The non-generic {1} '{0}' cannot be used with type arguments</source> <target state="translated">Neobecnou možnost {1} {0} nejde použít s argumenty typů.</target> <note /> </trans-unit> <trans-unit id="ERR_NewConstraintNotSatisfied"> <source>'{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">'Objekt {2} musí být neabstraktního typu s veřejným konstruktorem bez parametrů, jinak jej nejde použít jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedRefType"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný implicitní převod odkazu z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedNullableEnum"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedNullableInterface"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}. Typy s možnou hodnotou null nemůžou vyhovět žádným omezením rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedTyVar"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení ani převod typu parametru z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedValType"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateGeneratedName"> <source>The parameter name '{0}' conflicts with an automatically-generated parameter name</source> <target state="translated">Název parametru {0} je v konfliktu s automaticky generovaným názvem parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalSingleTypeNameNotFound"> <source>The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} se nenašel v globálním oboru názvů. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundMustBeLast"> <source>The new() constraint must be the last constraint specified</source> <target state="translated">Omezení new() musí být poslední zadané omezení.</target> <note /> </trans-unit> <trans-unit id="WRN_MainCantBeGeneric"> <source>'{0}': an entry point cannot be generic or in a generic type</source> <target state="translated">{0}: Vstupní bod nemůže být obecný nebo v obecném typu.</target> <note /> </trans-unit> <trans-unit id="WRN_MainCantBeGeneric_Title"> <source>An entry point cannot be generic or in a generic type</source> <target state="translated">Vstupní bod nemůže být obecný nebo v obecném typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarCantBeNull"> <source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source> <target state="translated">Hodnotu Null nejde převést na parametr typu {0}, protože by se mohlo jednat o typ, který nemůže mít hodnotu null. Zvažte možnost použití výrazu default({0}).</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateBound"> <source>Duplicate constraint '{0}' for type parameter '{1}'</source> <target state="translated">Duplicitní omezení {0} pro parametru typu {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ClassBoundNotFirst"> <source>The class type constraint '{0}' must come before any other constraints</source> <target state="translated">Omezení typu třídy {0} musí předcházet všem dalším omezením.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRetType"> <source>'{1} {0}' has the wrong return type</source> <target state="translated">{1} {0} má nesprávný návratový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateRefMismatch"> <source>Ref mismatch between '{0}' and delegate '{1}'</source> <target state="translated">Mezi {0} a delegátem {1} se neshoduje odkaz.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConstraintClause"> <source>A constraint clause has already been specified for type parameter '{0}'. All of the constraints for a type parameter must be specified in a single where clause.</source> <target state="translated">Klauzule omezení už byla přidaná pro parametr typu {0}. Všechna omezení pro parametr typu musí být zadaná v jediné klauzuli where.</target> <note /> </trans-unit> <trans-unit id="ERR_CantInferMethTypeArgs"> <source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source> <target state="translated">Argumenty typu pro metodu {0} nejde stanovit z použití. Zadejte argumenty typu explicitně.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalSameNameAsTypeParam"> <source>'{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter</source> <target state="translated">{0}: Parametr, místní proměnná nebo místní funkce nemůžou mít stejný název jako parametr typů metod.</target> <note /> </trans-unit> <trans-unit id="ERR_AsWithTypeVar"> <source>The type parameter '{0}' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint</source> <target state="translated">Parametr typu {0} nejde používat s operátorem as, protože nemá omezení typu třída ani omezení class.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedFieldAssg"> <source>The field '{0}' is assigned but its value is never used</source> <target state="translated">Pole {0} má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedFieldAssg_Title"> <source>Field is assigned but its value is never used</source> <target state="translated">Pole má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexerNameAttr"> <source>The '{0}' attribute is valid only on an indexer that is not an explicit interface member declaration</source> <target state="translated">Atribut {0} je platný jenom pro indexer, který nepředstavuje explicitní deklaraci člena rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrArgWithTypeVars"> <source>'{0}': an attribute argument cannot use type parameters</source> <target state="translated">{0}: Argument atributu nemůže používat parametry typů.</target> <note /> </trans-unit> <trans-unit id="ERR_NewTyvarWithArgs"> <source>'{0}': cannot provide arguments when creating an instance of a variable type</source> <target state="translated">{0}: Při vytváření instance typu proměnné nejde zadat argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractSealedStatic"> <source>'{0}': an abstract type cannot be sealed or static</source> <target state="translated">{0}: Abstraktní typ nemůže být sealed ani static.</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousXMLReference"> <source>Ambiguous reference in cref attribute: '{0}'. Assuming '{1}', but could have also matched other overloads including '{2}'.</source> <target state="translated">Nejednoznačný odkaz v atributu cref: {0}. Předpokládá se {1}, ale mohla se najít shoda s dalšími přetíženími, včetně {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousXMLReference_Title"> <source>Ambiguous reference in cref attribute</source> <target state="translated">Nejednoznačný odkaz v atributu cref</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef"> <source>'{0}': a reference to a volatile field will not be treated as volatile</source> <target state="translated">{0}: Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef_Title"> <source>A reference to a volatile field will not be treated as volatile</source> <target state="translated">Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef_Description"> <source>A volatile field should not normally be used as a ref or out value, since it will not be treated as volatile. There are exceptions to this, such as when calling an interlocked API.</source> <target state="translated">Pole s modifikátorem volatile by se normálně mělo používat jako hodnota Ref nebo Out, protože se s ním nebude zacházet jako s nestálým. Pro toto pravidlo platí výjimky, například při volání propojeného API.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithImpl"> <source>Since '{1}' has the ComImport attribute, '{0}' must be extern or abstract</source> <target state="translated">Protože {1} má atribut ComImport, {0} musí být externí nebo abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithBase"> <source>'{0}': a class with the ComImport attribute cannot specify a base class</source> <target state="translated">{0}: Třída s atributem ComImport nemůže určovat základní třídu.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplBadConstraints"> <source>The constraints for type parameter '{0}' of method '{1}' must match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead.</source> <target state="translated">Omezení pro parametr typu {0} metody {1} se musí shodovat s omezeními u parametru typu {2} metody rozhraní {3}. Místo toho zvažte použití explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplBadTupleNames"> <source>The tuple element names in the signature of method '{0}' must match the tuple element names of interface method '{1}' (including on the return type).</source> <target state="translated">Názvy prvků řazené kolekce členů v signatuře metody {0} se musí shodovat s názvy prvků řazené kolekce členů metody rozhraní {1} (a zároveň u návratového typu).</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInAgg"> <source>The type name '{0}' does not exist in the type '{1}'</source> <target state="translated">Název typu {0} neexistuje v typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MethGrpToNonDel"> <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source> <target state="translated">Nejde převést skupinu metod {0} na nedelegující typ {1}. Chtěli jste volat tuto metodu?</target> <note /> </trans-unit> <trans-unit id="ERR_BadExternAlias"> <source>The extern alias '{0}' was not specified in a /reference option</source> <target state="translated">Externí alias {0} nebyl zadaný jako možnost /reference.</target> <note /> </trans-unit> <trans-unit id="ERR_ColColWithTypeAlias"> <source>Cannot use alias '{0}' with '::' since the alias references a type. Use '.' instead.</source> <target state="translated">Zápis aliasu {0} se dvěma dvojtečkami (::) nejde použít, protože alias odkazuje na typ. Místo toho použijte zápis s tečkou (.).</target> <note /> </trans-unit> <trans-unit id="ERR_AliasNotFound"> <source>Alias '{0}' not found</source> <target state="translated">Alias {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameAggAgg"> <source>The type '{1}' exists in both '{0}' and '{2}'</source> <target state="translated">Typ {1} existuje v {0} i {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameNsAgg"> <source>The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}'</source> <target state="translated">Obor názvů {1} v {0} je v konfliktu s typem {3} v {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisNsAgg"> <source>The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'.</source> <target state="translated">Obor názvů {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se obor názvů definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisNsAgg_Title"> <source>Namespace conflicts with imported type</source> <target state="translated">Obor názvů je v konfliktu s importovaným typem.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggAgg"> <source>The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'.</source> <target state="translated">Typ {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se typ definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggAgg_Title"> <source>Type conflicts with imported type</source> <target state="translated">Typ je v konfliktu s importovaným typem.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggNs"> <source>The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'.</source> <target state="translated">Typ {1} v {0} je v konfliktu s importovaným oborem názvů {3} v {2}. Použije se typ definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggNs_Title"> <source>Type conflicts with imported namespace</source> <target state="translated">Typ je v konfliktu s importovaným oborem názvů.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameThisAggThisNs"> <source>The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}'</source> <target state="translated">Typ {1} v {0} je v konfliktu s oborem názvů {3} v {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternAfterElements"> <source>An extern alias declaration must precede all other elements defined in the namespace</source> <target state="translated">Deklarace externího aliasu musí předcházet všem ostatním prvkům definovaným v oboru názvů.</target> <note /> </trans-unit> <trans-unit id="WRN_GlobalAliasDefn"> <source>Defining an alias named 'global' is ill-advised since 'global::' always references the global namespace and not an alias</source> <target state="translated">Definování aliasu s názvem global se nedoporučuje, protože global:: vždycky odkazuje na globální obor názvů, ne na alias.</target> <note /> </trans-unit> <trans-unit id="WRN_GlobalAliasDefn_Title"> <source>Defining an alias named 'global' is ill-advised</source> <target state="translated">Definování aliasu s názvem global se nedoporučuje.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedStaticClass"> <source>'{0}': a type cannot be both static and sealed</source> <target state="translated">{0}: Typ nemůže být zároveň statický i zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_PrivateAbstractAccessor"> <source>'{0}': abstract properties cannot have private accessors</source> <target state="translated">{0}: Abstraktní vlastnosti nemůžou mít privátní přistupující objekty.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueExpected"> <source>Syntax error; value expected</source> <target state="translated">Chyba syntaxe: Očekávala se hodnota.</target> <note /> </trans-unit> <trans-unit id="ERR_UnboxNotLValue"> <source>Cannot modify the result of an unboxing conversion</source> <target state="translated">Nejde změnit výsledek unboxingového převodu.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonMethGrpInForEach"> <source>Foreach cannot operate on a '{0}'. Did you intend to invoke the '{0}'?</source> <target state="translated">Příkaz foreach nejde použít pro {0}. Měli jste v úmyslu vyvolat {0}?</target> <note /> </trans-unit> <trans-unit id="ERR_BadIncDecRetType"> <source>The return type for ++ or -- operator must match the parameter type or be derived from the parameter type</source> <target state="translated">Typ vrácené hodnoty operátorů ++ a -- musí odpovídat danému typu parametru nebo z něho musí být odvozený.</target> <note /> </trans-unit> <trans-unit id="ERR_RefValBoundWithClass"> <source>'{0}': cannot specify both a constraint class and the 'class' or 'struct' constraint</source> <target state="translated">{0}: Nejde zadat třídu omezení a zároveň omezení class nebo struct.</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundWithVal"> <source>The 'new()' constraint cannot be used with the 'struct' constraint</source> <target state="translated">Omezení new() nejde používat s omezením struct.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConstraintNotSatisfied"> <source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ odkazu, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ValConstraintNotSatisfied"> <source>The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ, který nemůže mít hodnotu null, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CircularConstraint"> <source>Circular constraint dependency involving '{0}' and '{1}'</source> <target state="translated">Cyklická závislost omezení zahrnující {0} a {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BaseConstraintConflict"> <source>Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'</source> <target state="translated">Parametr typu {0} dědí konfliktní omezení {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConWithValCon"> <source>Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'</source> <target state="translated">Parametr typu {1} má omezení struct, takže není možné používat {1} jako omezení pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigUDConv"> <source>Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'</source> <target state="translated">Při převodu typu {2} na typ {3} došlo k uživatelem definovaným nejednoznačným převodům typu {0} na typ {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_AlwaysNull"> <source>The result of the expression is always 'null' of type '{0}'</source> <target state="translated">Výsledek výrazu je vždy hodnota null typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_AlwaysNull_Title"> <source>The result of the expression is always 'null'</source> <target state="translated">Výsledek výrazu je vždycky null.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnThis"> <source>Cannot return 'this' by reference.</source> <target state="translated">Nejde vrátit this pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeCtorInParameter"> <source>Cannot use attribute constructor '{0}' because it has 'in' parameters.</source> <target state="translated">Nejde použít konstruktor atributu {0}, protože má parametry in.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithConstraints"> <source>Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint.</source> <target state="translated">Omezení pro metody přepsání a explicitní implementace rozhraní se dědí ze základní metody, nejde je tedy zadat přímo, s výjimkou omezení class nebo struct.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigOverride"> <source>The inherited members '{0}' and '{1}' have the same signature in type '{2}', so they cannot be overridden</source> <target state="translated">Zděděné členy {0} a {1} mají stejný podpis v typu {2}, takže je nejde přepsat.</target> <note /> </trans-unit> <trans-unit id="ERR_DecConstError"> <source>Evaluation of the decimal constant expression failed</source> <target state="translated">Vyhodnocování výrazu desítkové konstanty se nepovedlo.</target> <note /> </trans-unit> <trans-unit id="WRN_CmpAlwaysFalse"> <source>Comparing with null of type '{0}' always produces 'false'</source> <target state="translated">Výsledkem porovnání s hodnotou null typu {0} je vždycky false.</target> <note /> </trans-unit> <trans-unit id="WRN_CmpAlwaysFalse_Title"> <source>Comparing with null of struct type always produces 'false'</source> <target state="translated">Výsledkem porovnání s typem struct je vždycky false.</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod"> <source>Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?</source> <target state="translated">Zavedení metody Finalize může vést k potížím s voláním destruktoru. Měli jste v úmyslu deklarovat destruktor?</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod_Title"> <source>Introducing a 'Finalize' method can interfere with destructor invocation</source> <target state="translated">Zavedení metody Finalize se může rušit s vyvoláním destruktoru.</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod_Description"> <source>This warning occurs when you create a class with a method whose signature is public virtual void Finalize. If such a class is used as a base class and if the deriving class defines a destructor, the destructor will override the base class Finalize method, not Finalize.</source> <target state="translated">Toto varování se objeví, pokud vytvoříte třídu s metodou, jejíž podpis je veřejný virtuální void Finalize. Pokud se taková třída používá jako základní třída a pokud odvozující třída definuje destruktor, přepíše tento destruktor metodu Finalize základní třídy, ne samotné Finalize.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplParams"> <source>'{0}' should not have a params parameter since '{1}' does not</source> <target state="translated">'Pro {0} by neměl být nastavený parametr params, protože {1} ho nemá.</target> <note /> </trans-unit> <trans-unit id="WRN_GotoCaseShouldConvert"> <source>The 'goto case' value is not implicitly convertible to type '{0}'</source> <target state="translated">Hodnotu goto case nejde implicitně převést na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_GotoCaseShouldConvert_Title"> <source>The 'goto case' value is not implicitly convertible to the switch type</source> <target state="translated">Hodnotu goto case nejde implicitně převést na typ přepínače.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodImplementingAccessor"> <source>Method '{0}' cannot implement interface accessor '{1}' for type '{2}'. Use an explicit interface implementation.</source> <target state="translated">Metoda {0} nemůže implementovat přistupující objekt rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool"> <source>The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'</source> <target state="translated">Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool_Title"> <source>The result of the expression is always the same since a value of this type is never equal to 'null'</source> <target state="translated">Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool2"> <source>The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'</source> <target state="translated">Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool2_Title"> <source>The result of the expression is always the same since a value of this type is never equal to 'null'</source> <target state="translated">Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null.</target> <note /> </trans-unit> <trans-unit id="WRN_ExplicitImplCollision"> <source>Explicit interface implementation '{0}' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead.</source> <target state="translated">Explicitní implementace rozhraní {0} odpovídá víc než jednomu členovi rozhraní. Konkrétní výběr člena rozhraní závisí na implementaci. Zvažte možnost použití neexplicitní implementace.</target> <note /> </trans-unit> <trans-unit id="WRN_ExplicitImplCollision_Title"> <source>Explicit interface implementation matches more than one interface member</source> <target state="translated">Explicitní implementace rozhraní se shoduje s víc než jedním členem rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractHasBody"> <source>'{0}' cannot declare a body because it is marked abstract</source> <target state="translated">{0} nemůže deklarovat tělo, protože je označené jako abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_ConcreteMissingBody"> <source>'{0}' must declare a body because it is not marked abstract, extern, or partial</source> <target state="translated">{0} musí deklarovat tělo, protože je označené jako abstraktní, externí nebo částečné.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAndSealed"> <source>'{0}' cannot be both abstract and sealed</source> <target state="translated">{0} nemůže být extern i sealed.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractNotVirtual"> <source>The abstract {0} '{1}' cannot be marked virtual</source> <target state="translated">Abstraktní {0} {1} nelze označit jako virtuální.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstant"> <source>The constant '{0}' cannot be marked static</source> <target state="translated">Konstanta {0} nemůže být označená jako statická.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonFunction"> <source>'{0}': cannot override because '{1}' is not a function</source> <target state="translated">{0}: Nejde přepsat, protože {1} není funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonVirtual"> <source>'{0}': cannot override inherited member '{1}' because it is not marked virtual, abstract, or override</source> <target state="translated">{0}: Nejde přepsat zděděný člen {1}, protože není označený jako virtuální, abstraktní nebo přepis.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeAccessOnOverride"> <source>'{0}': cannot change access modifiers when overriding '{1}' inherited member '{2}'</source> <target state="translated">{0}: Při přepsání {1} zděděného členu {2} nejde měnit modifikátory přístupu.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeTupleNamesOnOverride"> <source>'{0}': cannot change tuple element names when overriding inherited member '{1}'</source> <target state="translated">{0}: při přepisu zděděného člena {1} nelze změnit prvek řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeReturnTypeOnOverride"> <source>'{0}': return type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantDeriveFromSealedType"> <source>'{0}': cannot derive from sealed type '{1}'</source> <target state="translated">{0}: Nejde odvozovat ze zapečetěného typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractInConcreteClass"> <source>'{0}' is abstract but it is contained in non-abstract type '{1}'</source> <target state="translated">{0} je abstraktní, ale je obsažená v neabstraktním typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstructorWithExplicitConstructorCall"> <source>'{0}': static constructor cannot have an explicit 'this' or 'base' constructor call</source> <target state="translated">{0}: Statický konstruktor nemůže používat explicitní volání konstruktoru this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstructorWithAccessModifiers"> <source>'{0}': access modifiers are not allowed on static constructors</source> <target state="translated">{0}: Modifikátory přístupu nejsou povolené pro statické konstruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_RecursiveConstructorCall"> <source>Constructor '{0}' cannot call itself</source> <target state="translated">Konstruktor {0} nemůže volat sám sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_IndirectRecursiveConstructorCall"> <source>Constructor '{0}' cannot call itself through another constructor</source> <target state="translated">Konstruktor {0} nemůže volat sám sebe přes jiný konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectCallingBaseConstructor"> <source>'{0}' has no base class and cannot call a base constructor</source> <target state="translated">{0} nemá žádnou základní třídu a nemůže volat konstruktor base.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedTypeNotFound"> <source>Predefined type '{0}' is not defined or imported</source> <target state="translated">Předdefinovaný typ {0} není definovaný ani importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeNotFound"> <source>Predefined type '{0}' is not defined or imported</source> <target state="translated">Předdefinovaný typ {0} není definovaný ani importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeAmbiguous3"> <source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source> <target state="translated">Předdefinovaný typ {0} je deklarovaný v několika odkazovaných sestaveních: {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_StructWithBaseConstructorCall"> <source>'{0}': structs cannot call base class constructors</source> <target state="translated">{0}: Struktury nemůžou volat konstruktor základní třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_StructLayoutCycle"> <source>Struct member '{0}' of type '{1}' causes a cycle in the struct layout</source> <target state="translated">Člen struktury {0} typu {1} způsobuje cyklus v rozložení struktury.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainFields"> <source>Interfaces cannot contain instance fields</source> <target state="translated">Rozhraní nemůžou obsahovat pole instance.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainConstructors"> <source>Interfaces cannot contain instance constructors</source> <target state="translated">Rozhraní nemůžou obsahovat konstruktory instance.</target> <note /> </trans-unit> <trans-unit id="ERR_NonInterfaceInInterfaceList"> <source>Type '{0}' in interface list is not an interface</source> <target state="translated">Typ {0} v seznamu rozhraní není rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceInBaseList"> <source>'{0}' is already listed in interface list</source> <target state="translated">{0} je už uvedené v seznamu rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceWithTupleNamesInBaseList"> <source>'{0}' is already listed in the interface list on type '{2}' with different tuple element names, as '{1}'.</source> <target state="translated">{0} je již uvedeno v seznamu rozhraní u typu {2} s jinými názvy prvků řazené kolekce členů jako {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CycleInInterfaceInheritance"> <source>Inherited interface '{1}' causes a cycle in the interface hierarchy of '{0}'</source> <target state="translated">Zděděné rozhraní {1} způsobuje cyklus v hierarchii rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_HidingAbstractMethod"> <source>'{0}' hides inherited abstract member '{1}'</source> <target state="translated">{0} skryje zděděný abstraktní člen {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedAbstractMethod"> <source>'{0}' does not implement inherited abstract member '{1}'</source> <target state="translated">{0} neimplementuje zděděný abstraktní člen {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedInterfaceMember"> <source>'{0}' does not implement interface member '{1}'</source> <target state="translated">{0} neimplementuje člen rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectCantHaveBases"> <source>The class System.Object cannot have a base class or implement an interface</source> <target state="translated">Třída System.Object nemůže mít základní třídu ani nemůže implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitInterfaceImplementationNotInterface"> <source>'{0}' in explicit interface declaration is not an interface</source> <target state="translated">{0} v explicitní deklaraci rozhraní není rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceMemberNotFound"> <source>'{0}' in explicit interface declaration is not found among members of the interface that can be implemented</source> <target state="translated">{0} v explicitní deklaraci rozhraní se nenašel mezi členy rozhraní, které se dají implementovat.</target> <note /> </trans-unit> <trans-unit id="ERR_ClassDoesntImplementInterface"> <source>'{0}': containing type does not implement interface '{1}'</source> <target state="translated">{0}: Nadřazený typ neimplementuje rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitInterfaceImplementationInNonClassOrStruct"> <source>'{0}': explicit interface declaration can only be declared in a class, record, struct or interface</source> <target state="translated">{0}: Explicitní deklaraci rozhraní se dá použít jen ve třídě, záznamu, struktuře nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberNameSameAsType"> <source>'{0}': member names cannot be the same as their enclosing type</source> <target state="translated">{0}: Názvy členů nemůžou být stejné jako názvy jejich nadřazených typů.</target> <note /> </trans-unit> <trans-unit id="ERR_EnumeratorOverflow"> <source>'{0}': the enumerator value is too large to fit in its type</source> <target state="translated">{0}: Hodnota výčtu je pro příslušný typ moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonProperty"> <source>'{0}': cannot override because '{1}' is not a property</source> <target state="translated">{0}: Nejde přepsat, protože {1} není vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_NoGetToOverride"> <source>'{0}': cannot override because '{1}' does not have an overridable get accessor</source> <target state="translated">{0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSetToOverride"> <source>'{0}': cannot override because '{1}' does not have an overridable set accessor</source> <target state="translated">{0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt set.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyCantHaveVoidType"> <source>'{0}': property or indexer cannot have void type</source> <target state="translated">{0}: Vlastnost nebo indexer nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyWithNoAccessors"> <source>'{0}': property or indexer must have at least one accessor</source> <target state="translated">{0}: Vlastnost nebo indexer musí obsahovat aspoň jeden přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_NewVirtualInSealed"> <source>'{0}' is a new virtual member in sealed type '{1}'</source> <target state="translated">{0} je nový virtuální člen v zapečetěném typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyAddingAccessor"> <source>'{0}' adds an accessor not found in interface member '{1}'</source> <target state="translated">{0} přidává přistupující objekt, který se nenašel v členu rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyMissingAccessor"> <source>Explicit interface implementation '{0}' is missing accessor '{1}'</source> <target state="translated">V explicitní implementaci rozhraní {0} chybí přistupující objekt {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithInterface"> <source>'{0}': user-defined conversions to or from an interface are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na rozhraní nebo z něho nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithBase"> <source>'{0}': user-defined conversions to or from a base type are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na základní typ nebo z něj nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithDerived"> <source>'{0}': user-defined conversions to or from a derived type are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na odvozený typ nebo z něj nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentityConversion"> <source>User-defined operator cannot convert a type to itself</source> <target state="needs-review-translation">Uživatelem definovaný operátor nemůže převzít objekt nadřazeného typu a převést jej na objekt nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionNotInvolvingContainedType"> <source>User-defined conversion must convert to or from the enclosing type</source> <target state="translated">Uživatelem definovaný převod musí převádět na nadřazený typ nebo z nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConversionInClass"> <source>Duplicate user-defined conversion in type '{0}'</source> <target state="translated">Duplicitní uživatelem definovaný převod v typu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorsMustBeStatic"> <source>User-defined operator '{0}' must be declared static and public</source> <target state="translated">Uživatelem definovaný operátor {0} musí být deklarovaný jako static a public.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIncDecSignature"> <source>The parameter type for ++ or -- operator must be the containing type</source> <target state="translated">Typ parametru operátorů ++ a -- musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnaryOperatorSignature"> <source>The parameter of a unary operator must be the containing type</source> <target state="translated">Parametr unárního operátoru musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinaryOperatorSignature"> <source>One of the parameters of a binary operator must be the containing type</source> <target state="translated">Jeden z parametrů binárního operátoru musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadShiftOperatorSignature"> <source>The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int</source> <target state="translated">První operand přetěžovaného operátoru shift musí být stejného typu jako obsahující typ a druhý operand musí být typu int.</target> <note /> </trans-unit> <trans-unit id="ERR_EnumsCantContainDefaultConstructor"> <source>Enums cannot contain explicit parameterless constructors</source> <target state="translated">Výčty nemůžou obsahovat explicitní konstruktory bez parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideBogusMethod"> <source>'{0}': cannot override '{1}' because it is not supported by the language</source> <target state="translated">{0} nemůže přepsat {1}, protože ho tento jazyk nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogus"> <source>'{0}' is not supported by the language</source> <target state="translated">{0} není tímto jazykem podporovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_CantCallSpecialMethod"> <source>'{0}': cannot explicitly call operator or accessor</source> <target state="translated">{0}: Nejde explicitně volat operátor nebo přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeReference"> <source>'{0}': cannot reference a type through an expression; try '{1}' instead</source> <target state="translated">{0}: Nemůže odkazovat na typ prostřednictvím výrazu. Místo toho zkuste {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDestructorName"> <source>Name of destructor must match name of type</source> <target state="translated">Název destruktoru musí odpovídat názvu typu.</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyClassesCanContainDestructors"> <source>Only class types can contain destructors</source> <target state="translated">Destruktor může být obsažený jenom v typu třída.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictAliasAndMember"> <source>Namespace '{1}' contains a definition conflicting with alias '{0}'</source> <target state="translated">Obor názvů {1} obsahuje definici, která je v konfliktu s aliasem {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingAliasAndDefinition"> <source>Alias '{0}' conflicts with {1} definition</source> <target state="translated">Alias {0} je v konfliktu s definicí {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnSpecialMethod"> <source>The Conditional attribute is not valid on '{0}' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation</source> <target state="needs-review-translation">Atribut Conditional není pro {0} platný, protože je to konstruktor, destruktor, operátor nebo explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalMustReturnVoid"> <source>The Conditional attribute is not valid on '{0}' because its return type is not void</source> <target state="translated">Atribut Conditional není pro {0} platný, protože jeho návratový kód není void.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAttribute"> <source>Duplicate '{0}' attribute</source> <target state="translated">Duplicitní atribut {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAttributeInNetModule"> <source>Duplicate '{0}' attribute in '{1}'</source> <target state="translated">Duplicitní atribut {0} v {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnInterfaceMethod"> <source>The Conditional attribute is not valid on interface members</source> <target state="translated">Pro členy rozhraní je atribut Conditional neplatný.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorCantReturnVoid"> <source>User-defined operators cannot return void</source> <target state="translated">Operátory definované uživatelem nemůžou vracet typ void.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicConversion"> <source>'{0}': user-defined conversions to or from the dynamic type are not allowed</source> <target state="translated">{0}: Uživatelsky definované převody na dynamický typ nebo z dynamického typu nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeArgument"> <source>Invalid value for argument to '{0}' attribute</source> <target state="translated">Neplatná hodnota pro argument u atributu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterNotValidForType"> <source>Parameter not valid for the specified unmanaged type.</source> <target state="translated">Parametr není platný pro zadaný nespravovaný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired1"> <source>Attribute parameter '{0}' must be specified.</source> <target state="translated">Parametr atributu {0} musí být zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired2"> <source>Attribute parameter '{0}' or '{1}' must be specified.</source> <target state="translated">Parametr atributu {0} nebo {1} musí být zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields"> <source>Unmanaged type '{0}' not valid for fields.</source> <target state="translated">Nespravovaný typ {0} není platný pro pole.</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields"> <source>Unmanaged type '{0}' is only valid for fields.</source> <target state="translated">Nespravovaný typ {0} je platný jenom pro pole.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOnBadSymbolType"> <source>Attribute '{0}' is not valid on this declaration type. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro deklaraci tohoto typu. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FloatOverflow"> <source>Floating-point constant is outside the range of type '{0}'</source> <target state="translated">Konstanta s pohyblivou řádovou čárkou je mimo rozsah typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithoutUuidAttribute"> <source>The Guid attribute must be specified with the ComImport attribute</source> <target state="translated">Atribut Guid musí být zadaný současně s atributem ComImport.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNamedArgument"> <source>Invalid value for named attribute argument '{0}'</source> <target state="translated">Neplatná hodnota argumentu {0} pojmenovaného atributu</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInvalidMethod"> <source>The DllImport attribute must be specified on a method marked 'static' and 'extern'</source> <target state="translated">Pro metodu s deklarací static a extern musí být zadaný atribut DllImport.</target> <note /> </trans-unit> <trans-unit id="ERR_EncUpdateFailedMissingAttribute"> <source>Cannot update '{0}'; attribute '{1}' is missing.</source> <target state="translated">Nelze aktualizovat {0}; chybí atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnGenericMethod"> <source>The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.</source> <target state="translated">Atribut DllImport se nedá použít u metody, která je obecná nebo obsažená v obecné metodě nebo typu.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldCantBeRefAny"> <source>Field or property cannot be of type '{0}'</source> <target state="translated">Pole nebo vlastnost nemůže být typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldAutoPropCantBeByRefLike"> <source>Field or auto-implemented property cannot be of type '{0}' unless it is an instance member of a ref struct.</source> <target state="translated">Vlastnost pole nebo automaticky implementovaná vlastnost nemůže být typu {0}, pokud není členem instance struktury REF.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayElementCantBeRefAny"> <source>Array elements cannot be of type '{0}'</source> <target state="translated">Prvky pole nemůžou být typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbol"> <source>'{0}' is obsolete</source> <target state="translated">'Prvek {0} je zastaralý.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbol_Title"> <source>Type or member is obsolete</source> <target state="translated">Typ nebo člen je zastaralý.</target> <note /> </trans-unit> <trans-unit id="ERR_NotAnAttributeClass"> <source>'{0}' is not an attribute class</source> <target state="translated">{0} není třída atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedAttributeArgument"> <source>'{0}' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.</source> <target state="translated">{0} není platný argument pojmenovaného atributu. Argumenty pojmenovaného atributu musí být pole, pro která nebyla použitá deklarace readonly, static ani const, nebo vlastnosti pro čtení i zápis, které jsou veřejné a nejsou statické.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbolStr"> <source>'{0}' is obsolete: '{1}'</source> <target state="translated">{0} je zastaralá: {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbolStr_Title"> <source>Type or member is obsolete</source> <target state="translated">Typ nebo člen je zastaralý.</target> <note /> </trans-unit> <trans-unit id="ERR_DeprecatedSymbolStr"> <source>'{0}' is obsolete: '{1}'</source> <target state="translated">{0} je zastaralá: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerCantHaveVoidType"> <source>Indexers cannot have void type</source> <target state="translated">Indexer nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_VirtualPrivate"> <source>'{0}': virtual or abstract members cannot be private</source> <target state="translated">{0}: Virtuální nebo abstraktní členy nemůžou být privátní.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitToNonArrayType"> <source>Can only use array initializer expressions to assign to array types. Try using a new expression instead.</source> <target state="translated">Výrazy inicializátoru pole jde používat jenom pro přiřazení k typům pole. Zkuste použít výraz new.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitInBadPlace"> <source>Array initializers can only be used in a variable or field initializer. Try using a new expression instead.</source> <target state="translated">Inicializátory pole jde používat jenom v inicializátoru pole nebo proměnné. Zkuste použít výraz new.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingStructOffset"> <source>'{0}': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute</source> <target state="translated">{0}: Typy polí instance označené deklarací StructLayout(LayoutKind.Explicit) musí mít atribut FieldOffset.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternMethodNoImplementation"> <source>Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.</source> <target state="translated">Metoda, operátor nebo přistupující objekt {0} je označený jako externí a nemá žádné atributy. Zvažte možnost přidání atributu DllImport k určení externí implementace.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternMethodNoImplementation_Title"> <source>Method, operator, or accessor is marked external and has no attributes on it</source> <target state="translated">Metoda, operátor nebo přistupující objekt používá deklaraci external a nemá žádné atributy.</target> <note /> </trans-unit> <trans-unit id="WRN_ProtectedInSealed"> <source>'{0}': new protected member declared in sealed type</source> <target state="translated">{0}: V zapečetěném typu je deklarovaný nový chráněný člen.</target> <note /> </trans-unit> <trans-unit id="WRN_ProtectedInSealed_Title"> <source>New protected member declared in sealed type</source> <target state="translated">V zapečetěném typu je deklarovaný nový chráněný člen</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedByConditional"> <source>Conditional member '{0}' cannot implement interface member '{1}' in type '{2}'</source> <target state="translated">Podmíněný člen {0} nemůže implementovat člen rozhraní {1} v typu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalRefParam"> <source>ref and out are not valid in this context</source> <target state="translated">Atributy ref a out nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgumentToAttribute"> <source>The argument to the '{0}' attribute must be a valid identifier</source> <target state="translated">Argument atributu {0} musí být platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_StructOffsetOnBadStruct"> <source>The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)</source> <target state="translated">Atribut FieldOffset jde použít jenom pro členy typů s deklarací StructLayout(LayoutKind.Explicit).</target> <note /> </trans-unit> <trans-unit id="ERR_StructOffsetOnBadField"> <source>The FieldOffset attribute is not allowed on static or const fields</source> <target state="translated">Atribut FieldOffset není povolený pro pole typu static nebo const.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeUsageOnNonAttributeClass"> <source>Attribute '{0}' is only valid on classes derived from System.Attribute</source> <target state="translated">Atribut {0} je platný jenom pro třídy odvozené od třídy System.Attribute.</target> <note /> </trans-unit> <trans-unit id="WRN_PossibleMistakenNullStatement"> <source>Possible mistaken empty statement</source> <target state="translated">Možná chybný prázdný příkaz</target> <note /> </trans-unit> <trans-unit id="WRN_PossibleMistakenNullStatement_Title"> <source>Possible mistaken empty statement</source> <target state="translated">Možná chybný prázdný příkaz</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedAttributeArgument"> <source>'{0}' duplicate named attribute argument</source> <target state="translated">'Duplicitní argument pojmenovaného atributu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromEnumOrValueType"> <source>'{0}' cannot derive from special class '{1}'</source> <target state="translated">{0} se nemůže odvozovat ze speciální třídy {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMemberOnIndexedType"> <source>Cannot specify the DefaultMember attribute on a type containing an indexer</source> <target state="translated">Atribut DefaultMember nejde zadat pro typ obsahující indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_BogusType"> <source>'{0}' is a type not supported by the language</source> <target state="translated">'Typ {0} není tímto jazykem podporovaný.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedInternalField"> <source>Field '{0}' is never assigned to, and will always have its default value {1}</source> <target state="translated">Do pole {0} se nikdy nic nepřiřadí. Bude mít vždy výchozí hodnotu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedInternalField_Title"> <source>Field is never assigned to, and will always have its default value</source> <target state="translated">Do pole se nikdy nic nepřiřadí. Bude mít vždycky výchozí hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_CStyleArray"> <source>Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.</source> <target state="translated">Chybný deklarátor pole. Při deklaraci spravovaného pole musí být specifikátor rozměru uvedený před identifikátorem proměnné. Při deklaraci pole vyrovnávací paměti pevné velikosti uveďte před typem pole klíčové slovo fixed.</target> <note /> </trans-unit> <trans-unit id="WRN_VacuousIntegralComp"> <source>Comparison to integral constant is useless; the constant is outside the range of type '{0}'</source> <target state="translated">Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_VacuousIntegralComp_Title"> <source>Comparison to integral constant is useless; the constant is outside the range of the type</source> <target state="translated">Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAttributeClass"> <source>Cannot apply attribute class '{0}' because it is abstract</source> <target state="translated">Nejde použít třídu atributů {0}, protože je abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedAttributeArgumentType"> <source>'{0}' is not a valid named attribute argument because it is not a valid attribute parameter type</source> <target state="translated">{0} není platný argument pojmenovaného atributu, protože se nejedná o platný typ parametru atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPredefinedMember"> <source>Missing compiler required member '{0}.{1}'</source> <target state="translated">Požadovaný člen {0}.{1} kompilátoru se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeLocationOnBadDeclaration"> <source>'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored.</source> <target state="translated">{0} není platné umístění atributu pro tuto deklaraci. Platnými umístěními atributů pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeLocationOnBadDeclaration_Title"> <source>Not a valid attribute location for this declaration</source> <target state="translated">Není platné umístění atributu pro tuto deklaraci.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAttributeLocation"> <source>'{0}' is not a recognized attribute location. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored.</source> <target state="translated">{0} není známé umístění atributu. Platná umístění atributu pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAttributeLocation_Title"> <source>Not a recognized attribute location</source> <target state="translated">Není rozpoznané umístění atributu.</target> <note /> </trans-unit> <trans-unit id="WRN_EqualsWithoutGetHashCode"> <source>'{0}' overrides Object.Equals(object o) but does not override Object.GetHashCode()</source> <target state="translated">{0} přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualsWithoutGetHashCode_Title"> <source>Type overrides Object.Equals(object o) but does not override Object.GetHashCode()</source> <target state="translated">Typ přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutEquals"> <source>'{0}' defines operator == or operator != but does not override Object.Equals(object o)</source> <target state="translated">{0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o).</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutEquals_Title"> <source>Type defines operator == or operator != but does not override Object.Equals(object o)</source> <target state="translated">Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o).</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutGetHashCode"> <source>'{0}' defines operator == or operator != but does not override Object.GetHashCode()</source> <target state="translated">{0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutGetHashCode_Title"> <source>Type defines operator == or operator != but does not override Object.GetHashCode()</source> <target state="translated">Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="ERR_OutAttrOnRefParam"> <source>Cannot specify the Out attribute on a ref parameter without also specifying the In attribute.</source> <target state="translated">Nejde specifikovat atribut Out pro referenční parametr, když není současně specifikovaný atribut In.</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadRefKind"> <source>'{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}'</source> <target state="translated">{0} nemůže definovat přetíženou {1}, která se liší jenom v modifikátorech parametrů {2} a {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_LiteralDoubleCast"> <source>Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type</source> <target state="translated">Literály typu double nejde implicitně převést na typ {1}. Chcete-li vytvořit literál tohoto typu, použijte předponu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_IncorrectBooleanAssg"> <source>Assignment in conditional expression is always constant; did you mean to use == instead of = ?</source> <target state="translated">Přiřazení je v podmíněných výrazech vždy konstantní. Nechtěli jste spíše použít operátor == místo operátoru = ?</target> <note /> </trans-unit> <trans-unit id="WRN_IncorrectBooleanAssg_Title"> <source>Assignment in conditional expression is always constant</source> <target state="translated">Přiřazení je v podmíněných výrazech vždycky konstantní.</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedInStruct"> <source>'{0}': new protected member declared in struct</source> <target state="translated">{0}: Ve struktuře je deklarovaný nový chráněný člen.</target> <note /> </trans-unit> <trans-unit id="ERR_InconsistentIndexerNames"> <source>Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type</source> <target state="translated">Dva indexery mají stejný název. Atribut IndexerName musí být v rámci jednoho typu použitý se stejným názvem pro každý indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithUserCtor"> <source>A class with the ComImport attribute cannot have a user-defined constructor</source> <target state="translated">Třída s atributem ComImport nemůže mít konstruktor definovaný uživatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldCantHaveVoidType"> <source>Field cannot have void type</source> <target state="translated">Pole nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="WRN_NonObsoleteOverridingObsolete"> <source>Member '{0}' overrides obsolete member '{1}'. Add the Obsolete attribute to '{0}'.</source> <target state="translated">Člen {0} přepisuje zastaralý člen {1}. Přidejte ke členu {0} atribut Obsolete.</target> <note /> </trans-unit> <trans-unit id="WRN_NonObsoleteOverridingObsolete_Title"> <source>Member overrides obsolete member</source> <target state="translated">Člen přepisuje nezastaralý člen.</target> <note /> </trans-unit> <trans-unit id="ERR_SystemVoid"> <source>System.Void cannot be used from C# -- use typeof(void) to get the void type object</source> <target state="translated">Nejde použít konstrukci System.Void jazyka C#. Objekt typu void získáte pomocí syntaxe typeof(void).</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitParamArray"> <source>Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead.</source> <target state="translated">Nepoužívejte atribut System.ParamArrayAttribute. Použijte místo něj klíčové slovo params.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend"> <source>Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first</source> <target state="translated">Logický bitový operátor or se použil pro operand s rozšířeným podpisem. Zvažte nejprve možnost přetypování na menší nepodepsaný typ.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend_Title"> <source>Bitwise-or operator used on a sign-extended operand</source> <target state="translated">Bitový operátor or byl použitý pro operand s rozšířeným podpisem.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend_Description"> <source>The compiler implicitly widened and sign-extended a variable, and then used the resulting value in a bitwise OR operation. This can result in unexpected behavior.</source> <target state="translated">Kompilátor implicitně rozšířil proměnnou a doplnil k ní podpis. Výslednou hodnotu pak použil v bitovém porovnání NEBO operaci. Výsledkem může být neočekávané chování.</target> <note /> </trans-unit> <trans-unit id="ERR_VolatileStruct"> <source>'{0}': a volatile field cannot be of the type '{1}'</source> <target state="translated">{0}: Pole s modifikátorem volatile nemůže být {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_VolatileAndReadonly"> <source>'{0}': a field cannot be both volatile and readonly</source> <target state="translated">{0}: U pole nejde použít současně volatile i readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractField"> <source>The modifier 'abstract' is not valid on fields. Try using a property instead.</source> <target state="translated">Modifikátor abstract není pro pole platný. Místo něho zkuste použít vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_BogusExplicitImpl"> <source>'{0}' cannot implement '{1}' because it is not supported by the language</source> <target state="translated">{0} nemůže implementovat {1}, protože ho tento jazyk nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitMethodImplAccessor"> <source>'{0}' explicit method implementation cannot implement '{1}' because it is an accessor</source> <target state="translated">'Explicitní implementace metody {0} nemůže implementovat {1}, protože se jedná o přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="WRN_CoClassWithoutComImport"> <source>'{0}' interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute'</source> <target state="translated">'Rozhraní {0} s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CoClassWithoutComImport_Title"> <source>Interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute'</source> <target state="translated">Rozhraní s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalWithOutParam"> <source>Conditional member '{0}' cannot have an out parameter</source> <target state="translated">Podmíněný člen {0} nemůže mít parametr out.</target> <note /> </trans-unit> <trans-unit id="ERR_AccessorImplementingMethod"> <source>Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation.</source> <target state="translated">Přistupující objekt {0} nemůže implementovat člen rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasQualAsExpression"> <source>The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead.</source> <target state="translated">Kvalifikátor aliasu oboru názvů (::) se vždycky vyhodnotí jako typ nebo obor názvů, takže je tady neplatný. Místo něho zvažte použití kvalifikátoru . (tečka).</target> <note /> </trans-unit> <trans-unit id="ERR_DerivingFromATyVar"> <source>Cannot derive from '{0}' because it is a type parameter</source> <target state="translated">Nejde odvozovat z parametru {0}, protože je to parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeParameter"> <source>Duplicate type parameter '{0}'</source> <target state="translated">Duplicitní parametr typu {0}</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterTypeParameter"> <source>Type parameter '{0}' has the same name as the type parameter from outer type '{1}'</source> <target state="translated">Parametr typu {0} má stejný název jako parametr typu z vnějšího typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterTypeParameter_Title"> <source>Type parameter has the same name as the type parameter from outer type</source> <target state="translated">Parametr typu má stejný název jako parametr typu z vnějšího typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVariableSameAsParent"> <source>Type parameter '{0}' has the same name as the containing type, or method</source> <target state="translated">Parametr typu {0} má stejný název jako nadřazený typ nebo metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_UnifyingInterfaceInstantiations"> <source>'{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions</source> <target state="translated">{0} nemůže implementovat {1} a zároveň {2}, protože u některých náhrad parametrů typu může dojít k jejich sjednocení.</target> <note /> </trans-unit> <trans-unit id="ERR_TyVarNotFoundInConstraint"> <source>'{1}' does not define type parameter '{0}'</source> <target state="translated">{1} nedefinuje parametr typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBoundType"> <source>'{0}' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</source> <target state="translated">{0} není platné omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_SpecialTypeAsBound"> <source>Constraint cannot be special class '{0}'</source> <target state="translated">Omezení nemůže být speciální třída {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBound"> <source>Inconsistent accessibility: constraint type '{1}' is less accessible than '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ omezení {1} je míň dostupný než {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_LookupInTypeVariable"> <source>Cannot do member lookup in '{0}' because it is a type parameter</source> <target state="translated">Nejde vyhledávat člena v {0}, protože se jedná o parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstraintType"> <source>Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</source> <target state="translated">Neplatný typ omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_InstanceMemberInStaticClass"> <source>'{0}': cannot declare instance members in a static class</source> <target state="translated">{0}: Nejde deklarovat členy instance ve statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticBaseClass"> <source>'{1}': cannot derive from static class '{0}'</source> <target state="translated">{1}: Nejde odvodit ze statické třídy {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorInStaticClass"> <source>Static classes cannot have instance constructors</source> <target state="translated">Statické třídy nemůžou mít konstruktory instancí.</target> <note /> </trans-unit> <trans-unit id="ERR_DestructorInStaticClass"> <source>Static classes cannot contain destructors</source> <target state="translated">Statické třídy nemůžou obsahovat destruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_InstantiatingStaticClass"> <source>Cannot create an instance of the static class '{0}'</source> <target state="translated">Nejde vytvořit instanci statické třídy {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticDerivedFromNonObject"> <source>Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object.</source> <target state="translated">Statická třída {0} se nemůže odvozovat z typu {1}. Tyto třídy se musí odvozovat z objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticClassInterfaceImpl"> <source>'{0}': static classes cannot implement interfaces</source> <target state="translated">{0}: Statické třídy nemůžou implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_RefStructInterfaceImpl"> <source>'{0}': ref structs cannot implement interfaces</source> <target state="translated">{0}: Struktury REF nemůžou implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorInStaticClass"> <source>'{0}': static classes cannot contain user-defined operators</source> <target state="translated">{0}: Statické třídy nemůžou obsahovat operátory definované uživatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertToStaticClass"> <source>Cannot convert to static type '{0}'</source> <target state="translated">Nejde převést na statický typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintIsStaticClass"> <source>'{0}': static classes cannot be used as constraints</source> <target state="translated">{0}: Statické třídy nejde používat jako omezení.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericArgIsStaticClass"> <source>'{0}': static types cannot be used as type arguments</source> <target state="translated">{0}: Statické typy nejde používat jako argumenty typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayOfStaticClass"> <source>'{0}': array elements cannot be of static type</source> <target state="translated">{0}: Prvky pole nemůžou být statického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerInStaticClass"> <source>'{0}': cannot declare indexers in a static class</source> <target state="translated">{0}: Nejde deklarovat indexery ve statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterIsStaticClass"> <source>'{0}': static types cannot be used as parameters</source> <target state="translated">{0}: Statické typy nejde používat jako parametry.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnTypeIsStaticClass"> <source>'{0}': static types cannot be used as return types</source> <target state="translated">{0}: Statické typy nejde používat jako typy vracených hodnot.</target> <note /> </trans-unit> <trans-unit id="ERR_VarDeclIsStaticClass"> <source>Cannot declare a variable of static type '{0}'</source> <target state="translated">Nejde deklarovat proměnnou statického typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyThrowInFinally"> <source>A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause</source> <target state="translated">Příkaz throw bez argumentů není povolený v klauzuli finally, která je vnořená do nejbližší uzavírající klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSpecifier"> <source>'{0}' is not a valid format specifier</source> <target state="translated">{0} není platným specifikátorem formátu.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToLockOrDispose"> <source>Possibly incorrect assignment to local '{0}' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.</source> <target state="translated">Možná existuje nesprávné přiřazení místní proměnné {0}, která je argumentem příkazu using nebo lock. Volání Dispose nebo odemknutí se provede u původní hodnoty místní proměnné.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToLockOrDispose_Title"> <source>Possibly incorrect assignment to local which is the argument to a using or lock statement</source> <target state="translated">Pravděpodobně nesprávné přiřazení místní hodnotě, která je argumentem příkazu using nebo lock</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeInThisAssembly"> <source>Type '{0}' is defined in this assembly, but a type forwarder is specified for it</source> <target state="translated">V tomto sestavení je definovaný typ {0}, je ale pro něj zadané předávání typů.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeIsNested"> <source>Cannot forward type '{0}' because it is a nested type of '{1}'</source> <target state="translated">Nejde předat typ {0}, protože se jedná o vnořený typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CycleInTypeForwarder"> <source>The type forwarder for type '{0}' in assembly '{1}' causes a cycle</source> <target state="translated">Předávání typů pro typ {0} v sestavení {1} způsobuje zacyklení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblyNameOnNonModule"> <source>The /moduleassemblyname option may only be specified when building a target type of 'module'</source> <target state="translated">Parametr /moduleassemblyname jde zadat jenom při vytváření typu cíle module.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFwdType"> <source>Invalid type specified as an argument for TypeForwardedTo attribute</source> <target state="translated">Neplatný typ zadaný jako argument atributu TypeForwardedTo</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberStatic"> <source>'{0}' does not implement instance interface member '{1}'. '{2}' cannot implement the interface member because it is static.</source> <target state="needs-review-translation">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože je statické.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberNotPublic"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement an interface member because it is not public.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože není veřejné.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongReturnType"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have the matching return type of '{3}'.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen {1}, protože nemá odpovídající návratový typ {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeForwarder"> <source>'{0}' duplicate TypeForwardedToAttribute</source> <target state="translated">'Duplicitní TypeForwardedToAttribute {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSelectOrGroup"> <source>A query body must end with a select clause or a group clause</source> <target state="translated">Za tělem dotazu musí následovat klauzule select nebo group.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordOn"> <source>Expected contextual keyword 'on'</source> <target state="translated">Očekávalo se kontextové klíčové slovo on.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordEquals"> <source>Expected contextual keyword 'equals'</source> <target state="translated">Očekávalo se kontextové klíčové slovo equals.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordBy"> <source>Expected contextual keyword 'by'</source> <target state="translated">Očekávalo se kontextové klíčové slovo by.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAnonymousTypeMemberDeclarator"> <source>Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.</source> <target state="translated">Neplatný deklarátor členu anonymního typu. Členy anonymního typu musí být deklarované přiřazením členu, prostým názvem nebo přístupem k členu.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInitializerElementInitializer"> <source>Invalid initializer member declarator</source> <target state="translated">Neplatný deklarátor členu inicializátoru</target> <note /> </trans-unit> <trans-unit id="ERR_InconsistentLambdaParameterUsage"> <source>Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit</source> <target state="translated">Nekonzistentní použití parametru lambda. Typy parametrů musí být buď všechny explicitní, nebo všechny implicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInvalidModifier"> <source>A partial method cannot have the 'abstract' modifier</source> <target state="translated">Částečná metoda nemůže mít modifikátor abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyInPartialClass"> <source>A partial method must be declared within a partial type</source> <target state="translated">Částečná metoda musí být deklarovaná uvnitř částečného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodNotExplicit"> <source>A partial method may not explicitly implement an interface method</source> <target state="translated">Částečná metoda nesmí explicitně implementovat metodu rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodExtensionDifference"> <source>Both partial method declarations must be extension methods or neither may be an extension method</source> <target state="translated">Obě deklarace částečné metody musí deklarovat metody rozšíření, nebo nesmí metodu rozšíření deklarovat žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyOneLatent"> <source>A partial method may not have multiple defining declarations</source> <target state="translated">Částečná metoda nesmí mít víc definujících deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyOneActual"> <source>A partial method may not have multiple implementing declarations</source> <target state="translated">Částečná metoda nesmí mít víc implementujících deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamsDifference"> <source>Both partial method declarations must use a params parameter or neither may use a params parameter</source> <target state="translated">Obě deklarace částečné metody musí používat parametr params nebo ho nepoužívat.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodMustHaveLatent"> <source>No defining declaration found for implementing declaration of partial method '{0}'</source> <target state="translated">Nenašla se žádná definující deklarace pro implementující deklaraci částečné metody {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInconsistentTupleNames"> <source>Both partial method declarations, '{0}' and '{1}', must use the same tuple element names.</source> <target state="translated">V deklaracích metod, {0} a {1} se musí používat stejné názvy prvků řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInconsistentConstraints"> <source>Partial method declarations of '{0}' have inconsistent constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace metod {0} mají nekonzistentní omezení parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodToDelegate"> <source>Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration</source> <target state="translated">Nejde vytvořit delegáta z metody {0}, protože se jedná o částečnou metodu bez implementující deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodStaticDifference"> <source>Both partial method declarations must be static or neither may be static</source> <target state="translated">Obě deklarace částečné metody musí být statické, nebo nesmí být statická žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodUnsafeDifference"> <source>Both partial method declarations must be unsafe or neither may be unsafe</source> <target state="translated">Obě deklarace částečné metody musí být nezabezpečené, nebo nesmí být nezabezpečená žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInExpressionTree"> <source>Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees</source> <target state="translated">Ve stromech výrazů nejde používat částečné metody, pro které existuje jenom definující deklarace, nebo odebrané podmíněné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteOverridingNonObsolete"> <source>Obsolete member '{0}' overrides non-obsolete member '{1}'</source> <target state="translated">Zastaralý člen {0} potlačuje nezastaralý člen {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteOverridingNonObsolete_Title"> <source>Obsolete member overrides non-obsolete member</source> <target state="translated">Zastaralý člen přepisuje nezastaralý člen.</target> <note /> </trans-unit> <trans-unit id="WRN_DebugFullNameTooLong"> <source>The fully qualified name for '{0}' is too long for debug information. Compile without '/debug' option.</source> <target state="translated">Plně kvalifikovaný název {0} je moc dlouhý pro vygenerování ladicích informací. Z kompilace vyřaďte možnost /debug.</target> <note /> </trans-unit> <trans-unit id="WRN_DebugFullNameTooLong_Title"> <source>Fully qualified name is too long for debug information</source> <target state="translated">Plně kvalifikovaný název je pro ladicí informace moc dlouhý.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableAssignedBadValue"> <source>Cannot assign {0} to an implicitly-typed variable</source> <target state="translated">{0} nejde přiřadit k proměnné s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableWithNoInitializer"> <source>Implicitly-typed variables must be initialized</source> <target state="translated">Proměnné s implicitním typem musí být inicializované.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableMultipleDeclarator"> <source>Implicitly-typed variables cannot have multiple declarators</source> <target state="translated">Proměnné s implicitním typem nemůžou mít víc deklarátorů.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableAssignedArrayInitializer"> <source>Cannot initialize an implicitly-typed variable with an array initializer</source> <target state="translated">Proměnnou s implicitním typem nejde inicializovat inicializátorem pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedLocalCannotBeFixed"> <source>Implicitly-typed local variables cannot be fixed</source> <target state="translated">Lokální proměnné s implicitním typem nemůžou být pevné.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableCannotBeConst"> <source>Implicitly-typed variables cannot be constant</source> <target state="translated">Proměnné s implicitním typem nemůžou být konstanty.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternCtorNoImplementation"> <source>Constructor '{0}' is marked external</source> <target state="translated">Konstruktor {0} je označený jako externí.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternCtorNoImplementation_Title"> <source>Constructor is marked external</source> <target state="translated">Konstruktor je označený jako externí.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarNotFound"> <source>The contextual keyword 'var' may only appear within a local variable declaration or in script code</source> <target state="translated">Kontextové klíčové slovo var se může objevit pouze v rámci deklarace lokální proměnné nebo v kódu skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedArrayNoBestType"> <source>No best type found for implicitly-typed array</source> <target state="translated">Nebyl nalezen optimální typ pro implicitně typované pole.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypePropertyAssignedBadValue"> <source>Cannot assign '{0}' to anonymous type property</source> <target state="translated">{0} nejde přiřadit k anonymní vlastnosti typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsBaseAccess"> <source>An expression tree may not contain a base access</source> <target state="translated">Strom výrazu nesmí obsahovat základní přístup.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAssignment"> <source>An expression tree may not contain an assignment operator</source> <target state="translated">Strom výrazu nesmí obsahovat operátor přiřazení.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeDuplicatePropertyName"> <source>An anonymous type cannot have multiple properties with the same name</source> <target state="translated">Anonymní typ nemůže mít více vlastností se stejným názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_StatementLambdaToExpressionTree"> <source>A lambda expression with a statement body cannot be converted to an expression tree</source> <target state="translated">Výraz lambda s tělem příkazu nejde převést na strom výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeMustHaveDelegate"> <source>Cannot convert lambda to an expression tree whose type argument '{0}' is not a delegate type</source> <target state="translated">Výraz lambda nejde převést na strom výrazu, jehož argument typu {0} neurčuje delegovaný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNotAvailable"> <source>Cannot use anonymous type in a constant expression</source> <target state="translated">V konstantním výrazu nejde použít anonymní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaInIsAs"> <source>The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.</source> <target state="translated">Prvním operandem operátoru is nebo as nesmí být výraz lambda, anonymní metoda ani skupina metod.</target> <note /> </trans-unit> <trans-unit id="ERR_TypelessTupleInAs"> <source>The first operand of an 'as' operator may not be a tuple literal without a natural type.</source> <target state="translated">První operand operátoru as nesmí být literál řazené kolekce členů bez přirozeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer"> <source>An expression tree may not contain a multidimensional array initializer</source> <target state="translated">Strom výrazu nesmí obsahovat inicializátor vícedimenzionálního pole.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingArgument"> <source>Argument missing</source> <target state="translated">Chybí argument.</target> <note /> </trans-unit> <trans-unit id="ERR_VariableUsedBeforeDeclaration"> <source>Cannot use local variable '{0}' before it is declared</source> <target state="translated">Lokální proměnnou {0} nejde použít dřív, než je deklarovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_RecursivelyTypedVariable"> <source>Type of '{0}' cannot be inferred since its initializer directly or indirectly refers to the definition.</source> <target state="translated">Typ pro {0} nejde odvodit, protože jeho inicializátor přímo nebo nepřímo odkazuje na definici.</target> <note /> </trans-unit> <trans-unit id="ERR_UnassignedThisAutoProperty"> <source>Auto-implemented property '{0}' must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu modulu musí být plně přiřazená automaticky implementovaná vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_VariableUsedBeforeDeclarationAndHidesField"> <source>Cannot use local variable '{0}' before it is declared. The declaration of the local variable hides the field '{1}'.</source> <target state="translated">Lokální proměnnou {0} nejde použít dřív, než je deklarovaná. Deklarace lokální proměnné skryje pole {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsBadCoalesce"> <source>An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side</source> <target state="translated">Strom výrazu lambda nesmí obsahovat operátor sloučení, na jehož levé straně stojí literál s hodnotou Null nebo výchozí literál.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentifierExpected"> <source>Identifier expected</source> <target state="translated">Očekával se identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_SemicolonExpected"> <source>; expected</source> <target state="translated">Očekával se středník (;).</target> <note /> </trans-unit> <trans-unit id="ERR_SyntaxError"> <source>Syntax error, '{0}' expected</source> <target state="translated">Chyba syntaxe; očekávána hodnota: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateModifier"> <source>Duplicate '{0}' modifier</source> <target state="translated">Duplicitní modifikátor {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAccessor"> <source>Property accessor already defined</source> <target state="translated">Přistupující objekt vlastnosti je už definovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralTypeExpected"> <source>Type byte, sbyte, short, ushort, int, uint, long, or ulong expected</source> <target state="translated">Očekával se typ byte, sbyte, short, ushort, int, uint, long nebo ulong.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalEscape"> <source>Unrecognized escape sequence</source> <target state="translated">Nerozpoznaná řídicí sekvence</target> <note /> </trans-unit> <trans-unit id="ERR_NewlineInConst"> <source>Newline in constant</source> <target state="translated">Konstanta obsahuje znak nového řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyCharConst"> <source>Empty character literal</source> <target state="translated">Prázdný znakový literál</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyCharsInConst"> <source>Too many characters in character literal</source> <target state="translated">Příliš moc znaků ve znakovém literálu</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNumber"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="ERR_GetOrSetExpected"> <source>A get or set accessor expected</source> <target state="translated">Očekával se přistupující objekt get nebo set.</target> <note /> </trans-unit> <trans-unit id="ERR_ClassTypeExpected"> <source>An object, string, or class type expected</source> <target state="translated">Očekával se typ object, string nebo class.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentExpected"> <source>Named attribute argument expected</source> <target state="translated">Očekával se argument pojmenovaného atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyCatches"> <source>Catch clauses cannot follow the general catch clause of a try statement</source> <target state="translated">Klauzule catch nemůžou následovat za obecnou klauzulí catch příkazu try.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisOrBaseExpected"> <source>Keyword 'this' or 'base' expected</source> <target state="translated">Očekávalo se klíčové slovo this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlUnaryOperatorExpected"> <source>Overloadable unary operator expected</source> <target state="translated">Očekával se přetěžovatelný unární operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlBinaryOperatorExpected"> <source>Overloadable binary operator expected</source> <target state="translated">Očekával se přetěžovatelný binární operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_IntOverflow"> <source>Integral constant is too large</source> <target state="translated">Integrální konstanta je moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_EOFExpected"> <source>Type or namespace definition, or end-of-file expected</source> <target state="translated">Očekávala se definice typu nebo oboru názvů, nebo konec souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalDefinitionOrStatementExpected"> <source>Member definition, statement, or end-of-file expected</source> <target state="translated">Očekává se definice člena, příkaz nebo konec souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmbeddedStmt"> <source>Embedded statement cannot be a declaration or labeled statement</source> <target state="translated">Vloženým příkazem nemůže být deklarace ani příkaz s návěstím.</target> <note /> </trans-unit> <trans-unit id="ERR_PPDirectiveExpected"> <source>Preprocessor directive expected</source> <target state="translated">Očekávala se direktiva preprocesoru.</target> <note /> </trans-unit> <trans-unit id="ERR_EndOfPPLineExpected"> <source>Single-line comment or end-of-line expected</source> <target state="translated">Očekával se jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseParenExpected"> <source>) expected</source> <target state="translated">Očekává se ).</target> <note /> </trans-unit> <trans-unit id="ERR_EndifDirectiveExpected"> <source>#endif directive expected</source> <target state="translated">Očekávala se direktiva #endif.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedDirective"> <source>Unexpected preprocessor directive</source> <target state="translated">Neočekávaná direktiva preprocesoru</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorDirective"> <source>#error: '{0}'</source> <target state="translated">#error: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_WarningDirective"> <source>#warning: '{0}'</source> <target state="translated">#warning: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_WarningDirective_Title"> <source>#warning directive</source> <target state="translated">Direktiva #warning</target> <note /> </trans-unit> <trans-unit id="ERR_TypeExpected"> <source>Type expected</source> <target state="translated">Očekával se typ.</target> <note /> </trans-unit> <trans-unit id="ERR_PPDefFollowsToken"> <source>Cannot define/undefine preprocessor symbols after first token in file</source> <target state="translated">Po prvním tokenu v souboru nejde definovat symboly preprocesoru ani rušit jejich definice.</target> <note /> </trans-unit> <trans-unit id="ERR_PPReferenceFollowsToken"> <source>Cannot use #r after first token in file</source> <target state="translated">Nejde použít #r po prvním tokenu v souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_OpenEndedComment"> <source>End-of-file found, '*/' expected</source> <target state="translated">Našel se konec souboru. Očekával se řetězec */.</target> <note /> </trans-unit> <trans-unit id="ERR_Merge_conflict_marker_encountered"> <source>Merge conflict marker encountered</source> <target state="translated">Byla zjištěna značka konfliktu sloučení.</target> <note /> </trans-unit> <trans-unit id="ERR_NoRefOutWhenRefOnly"> <source>Do not use refout when using refonly.</source> <target state="translated">Když používáte refonly, nepoužívejte refout.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly"> <source>Cannot compile net modules when using /refout or /refonly.</source> <target state="translated">Když se používá přepínač /refout nebo /refonly, nejde zkompilovat síťové moduly.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlOperatorExpected"> <source>Overloadable operator expected</source> <target state="translated">Očekával se přetěžovatelný operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_EndRegionDirectiveExpected"> <source>#endregion directive expected</source> <target state="translated">Očekávala se direktiva #endregion.</target> <note /> </trans-unit> <trans-unit id="ERR_UnterminatedStringLit"> <source>Unterminated string literal</source> <target state="translated">Neukončený řetězcový literál</target> <note /> </trans-unit> <trans-unit id="ERR_BadDirectivePlacement"> <source>Preprocessor directives must appear as the first non-whitespace character on a line</source> <target state="translated">Direktivy preprocesoru musí být uvedené jako první neprázdné znaky na řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentifierExpectedKW"> <source>Identifier expected; '{1}' is a keyword</source> <target state="translated">Očekával se identifikátor; {1} je klíčové slovo.</target> <note /> </trans-unit> <trans-unit id="ERR_SemiOrLBraceExpected"> <source>{ or ; expected</source> <target state="translated">Očekávala se levá složená závorka ({) nebo středník (;).</target> <note /> </trans-unit> <trans-unit id="ERR_MultiTypeInDeclaration"> <source>Cannot use more than one type in a for, using, fixed, or declaration statement</source> <target state="translated">V příkazu deklarace for, using, fixed nebo or nejde použít více než jeden typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AddOrRemoveExpected"> <source>An add or remove accessor expected</source> <target state="translated">Očekával se přistupující objekt add nebo remove.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedCharacter"> <source>Unexpected character '{0}'</source> <target state="translated">Neočekávaný znak {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedToken"> <source>Unexpected token '{0}'</source> <target state="translated">Neočekávaný token {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedInStatic"> <source>'{0}': static classes cannot contain protected members</source> <target state="translated">{0}: Statické třídy nemůžou obsahovat chráněné členy.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch"> <source>A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException.</source> <target state="translated">Předchozí klauzule catch už zachycuje všechny výjimky. Všechny vyvolané události, které nejsou výjimkami, budou zahrnuty do obálky třídy System.Runtime.CompilerServices.RuntimeWrappedException.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch_Title"> <source>A previous catch clause already catches all exceptions</source> <target state="translated">Předchozí klauzule catch už zachytává všechny výjimky.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch_Description"> <source>This warning is caused when a catch() block has no specified exception type after a catch (System.Exception e) block. The warning advises that the catch() block will not catch any exceptions. A catch() block after a catch (System.Exception e) block can catch non-CLS exceptions if the RuntimeCompatibilityAttribute is set to false in the AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. If this attribute is not set explicitly to false, all thrown non-CLS exceptions are wrapped as Exceptions and the catch (System.Exception e) block catches them.</source> <target state="translated">Toto varování způsobuje, když blok catch() nemá žádný zadaný typ výjimky po bloku catch (System.Exception e). Varování informuje, že blok catch() nezachytí žádné výjimky. Blok catch() po bloku catch (System.Exception e) může zachytit výjimky, které nesouvisí se specifikací CLS, pokud je RuntimeCompatibilityAttribute nastavený na false v souboru AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Pokud tento atribut není nastavený explicitně na false, všechny výjimky, které nesouvisí se specifikací CLS, se dostanou do balíčku Exceptions a blok catch (System.Exception e) je zachytí.</target> <note /> </trans-unit> <trans-unit id="ERR_IncrementLvalueExpected"> <source>The operand of an increment or decrement operator must be a variable, property or indexer</source> <target state="translated">Operandem operátoru přičtení nebo odečtení musí být proměnná, vlastnost nebo indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMemberOrExtension"> <source>'{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)</source> <target state="translated">{0} neobsahuje definici pro {1} a nenašla se žádná dostupná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using nebo odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMemberOrExtensionNeedUsing"> <source>'{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive for '{2}'?)</source> <target state="translated">{0} neobsahuje definici pro {1} a nenašla se žádná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using pro {2}?)</target> <note /> </trans-unit> <trans-unit id="ERR_BadThisParam"> <source>Method '{0}' has a parameter modifier 'this' which is not on the first parameter</source> <target state="translated">Metoda {0} má modifikátor parametru this, který není na prvním parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParameterModifiers"> <source> The parameter modifier '{0}' cannot be used with '{1}'</source> <target state="translated"> Modifikátor parametru {0} nejde použít s modifikátorem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeforThis"> <source>The first parameter of an extension method cannot be of type '{0}'</source> <target state="translated">První parametr metody rozšíření nesmí být typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamModThis"> <source>A parameter array cannot be used with 'this' modifier on an extension method</source> <target state="translated">V metodě rozšíření nejde použít pole parametrů s modifikátorem this.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExtensionMeth"> <source>Extension method must be static</source> <target state="translated">Metoda rozšíření musí být statická.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExtensionAgg"> <source>Extension method must be defined in a non-generic static class</source> <target state="translated">Metoda rozšíření musí být definovaná v neobecné statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_DupParamMod"> <source>A parameter can only have one '{0}' modifier</source> <target state="translated">Parametr může mít jenom jeden modifikátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodsDecl"> <source>Extension methods must be defined in a top level static class; {0} is a nested class</source> <target state="translated">Metody rozšíření musí být definované ve statické třídě nejvyšší úrovně; {0} je vnořená třída.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionAttrNotFound"> <source>Cannot define a new extension method because the compiler required type '{0}' cannot be found. Are you missing a reference to System.Core.dll?</source> <target state="translated">Nejde definovat novou metodu rozšíření, protože se nenašel vyžadovaný typ kompilátoru {0}. Nechybí odkaz na System.Core.dll?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitExtension"> <source>Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.</source> <target state="translated">Nepoužívejte System.Runtime.CompilerServices.ExtensionAttribute. Místo toho použijte klíčové slovo this.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitDynamicAttr"> <source>Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead.</source> <target state="translated">Nepoužívejte System.Runtime.CompilerServices.DynamicAttribute. Místo toho použijte klíčové slovo dynamic.</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBaseCtor"> <source>The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.</source> <target state="translated">Volání konstruktoru je nutné volat dynamicky, což ale není možné, protože je součástí inicializátoru konstruktoru. Zvažte použití dynamických argumentů.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTypeExtDelegate"> <source>Extension method '{0}' defined on value type '{1}' cannot be used to create delegates</source> <target state="translated">Metoda rozšíření {0} definovaná v hodnotovém typu {1} se nedá použít k vytváření delegátů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgCount"> <source>No overload for method '{0}' takes {1} arguments</source> <target state="translated">Žádné přetížení pro metodu {0} nepřevezme tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgType"> <source>Argument {0}: cannot convert from '{1}' to '{2}'</source> <target state="translated">Argument {0}: Nejde převést z {1} na {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSourceFile"> <source>Source file '{0}' could not be opened -- {1}</source> <target state="translated">Zdrojový soubor {0} nešel otevřít -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CantRefResource"> <source>Cannot link resource files when building a module</source> <target state="translated">Při sestavování modulu nejde propojit soubory prostředků.</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceNotUnique"> <source>Resource identifier '{0}' has already been used in this assembly</source> <target state="translated">Identifikátor prostředku {0} se už v tomto sestavení používá.</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceFileNameNotUnique"> <source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly</source> <target state="translated">Každý propojený prostředek a modul musí mít jedinečný název souboru, ale {0} se v tomto sestavení objevuje víc než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_ImportNonAssembly"> <source>The referenced file '{0}' is not an assembly</source> <target state="translated">Odkazovaný soubor {0} není sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefLvalueExpected"> <source>A ref or out value must be an assignable variable</source> <target state="translated">Hodnotou Ref nebo Out musí být proměnná s možností přiřazení hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseInStaticMeth"> <source>Keyword 'base' is not available in a static method</source> <target state="translated">Klíčové slovo base není k dispozici uvnitř statické metody.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseInBadContext"> <source>Keyword 'base' is not available in the current context</source> <target state="translated">Klíčové slovo base není k dispozici v aktuálním kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_RbraceExpected"> <source>} expected</source> <target state="translated">Očekával se znak }.</target> <note /> </trans-unit> <trans-unit id="ERR_LbraceExpected"> <source>{ expected</source> <target state="translated">Očekával se znak {.</target> <note /> </trans-unit> <trans-unit id="ERR_InExpected"> <source>'in' expected</source> <target state="translated">'Očekávalo se klíčové slovo in.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocExpr"> <source>Invalid preprocessor expression</source> <target state="translated">Neplatný výraz preprocesoru</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMemberDecl"> <source>Invalid token '{0}' in class, record, struct, or interface member declaration</source> <target state="translated">Neplatný token {0} v deklaraci člena rozhraní, třídy, záznamu nebo struktury</target> <note /> </trans-unit> <trans-unit id="ERR_MemberNeedsType"> <source>Method must have a return type</source> <target state="translated">Metoda musí mít typ vrácené hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBaseType"> <source>Invalid base type</source> <target state="translated">Neplatný základní typ</target> <note /> </trans-unit> <trans-unit id="WRN_EmptySwitch"> <source>Empty switch block</source> <target state="translated">Prázdný blok switch</target> <note /> </trans-unit> <trans-unit id="WRN_EmptySwitch_Title"> <source>Empty switch block</source> <target state="translated">Prázdný blok switch</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndTry"> <source>Expected catch or finally</source> <target state="translated">Očekávalo se klíčové slovo catch nebo finally.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidExprTerm"> <source>Invalid expression term '{0}'</source> <target state="translated">Neplatný výraz {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadNewExpr"> <source>A new expression requires an argument list or (), [], or {} after type</source> <target state="translated">Výraz new vyžaduje za typem seznam argumentů nebo (), [] nebo {}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNamespacePrivate"> <source>Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected</source> <target state="translated">Elementy definované v názvovém prostoru nelze explicitně deklarovat jako private, protected, protected internal nebo private protected.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVarDecl"> <source>Expected ; or = (cannot specify constructor arguments in declaration)</source> <target state="translated">Očekával se znak ; nebo = (v deklaraci nejde zadat argumenty konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_UsingAfterElements"> <source>A using clause must precede all other elements defined in the namespace except extern alias declarations</source> <target state="translated">Klauzule using musí předcházet všem ostatním prvkům definovaným v oboru názvů s výjimkou deklarací externích aliasů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinOpArgs"> <source>Overloaded binary operator '{0}' takes two parameters</source> <target state="translated">Přetěžovaný binární operátor {0} používá dva parametry.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnOpArgs"> <source>Overloaded unary operator '{0}' takes one parameter</source> <target state="translated">Přetěžovaný unární operátor {0} převezme jeden parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_NoVoidParameter"> <source>Invalid parameter type 'void'</source> <target state="translated">Neplatný typ parametru void</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAlias"> <source>The using alias '{0}' appeared previously in this namespace</source> <target state="translated">Alias using {0} se objevil dřív v tomto oboru názvů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadProtectedAccess"> <source>Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)</source> <target state="translated">K chráněnému členu {0} nejde přistupovat prostřednictvím kvalifikátoru typu {1}. Kvalifikátor musí být typu {2} (nebo musí být od tohoto typu odvozen).</target> <note /> </trans-unit> <trans-unit id="ERR_AddModuleAssembly"> <source>'{0}' cannot be added to this assembly because it already is an assembly</source> <target state="translated">{0} se nemůže přidat do tohoto sestavení, protože už to sestavení je.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogusProp2"> <source>Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'</source> <target state="translated">Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metody přistupujícího objektu {1} nebo {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogusProp1"> <source>Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'</source> <target state="translated">Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metodu přistupujícího objektu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoVoidHere"> <source>Keyword 'void' cannot be used in this context</source> <target state="translated">Klíčové slovo void nejde v tomto kontextu použít.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerNeedsParam"> <source>Indexers must have at least one parameter</source> <target state="translated">Indexery musí mít nejmíň jeden parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArraySyntax"> <source>Array type specifier, [], must appear before parameter name</source> <target state="translated">Před názvem parametru musí být uvedený specifikátor typu pole [].</target> <note /> </trans-unit> <trans-unit id="ERR_BadOperatorSyntax"> <source>Declaration is not valid; use '{0} operator &lt;dest-type&gt; (...' instead</source> <target state="translated">Deklarace není platná. Místo toho použijte: {0} operátor &lt;dest-type&gt; (...</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassNotFound"> <source>Could not find '{0}' specified for Main method</source> <target state="translated">Prvek {0} zadaný pro metodu Main se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassNotClass"> <source>'{0}' specified for Main method must be a non-generic class, record, struct, or interface</source> <target state="translated">Typ {0} zadaný pro metodu Main musí být neobecná třída, záznam, struktura nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMainInClass"> <source>'{0}' does not have a suitable static 'Main' method</source> <target state="translated">{0} nemá vhodnou statickou metodu Main.</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassIsImport"> <source>Cannot use '{0}' for Main method because it is imported</source> <target state="translated">{0} nejde použít pro metodu Main, protože je importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_OutputNeedsName"> <source>Outputs without source must have the /out option specified</source> <target state="translated">U výstupu bez zdroje musí být zadaný přepínač /out.</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndManifest"> <source>Conflicting options specified: Win32 resource file; Win32 manifest</source> <target state="translated">Jsou zadané konfliktní možnosti: soubor prostředků Win32, manifest Win32.</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndIcon"> <source>Conflicting options specified: Win32 resource file; Win32 icon</source> <target state="translated">Jsou zadané konfliktní možnosti: soubor prostředků Win32, ikona Win32.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadResource"> <source>Error reading resource '{0}' -- '{1}'</source> <target state="translated">Chyba při čtení prostředku {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_DocFileGen"> <source>Error writing to XML documentation file: {0}</source> <target state="translated">Chyba při zápisu do souboru dokumentace XML: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseError"> <source>XML comment has badly formed XML -- '{0}'</source> <target state="translated">Komentáře XML má chybně vytvořený kód -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseError_Title"> <source>XML comment has badly formed XML</source> <target state="translated">Komentář XML má chybně vytvořený kód.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateParamTag"> <source>XML comment has a duplicate param tag for '{0}'</source> <target state="translated">Komentář XML má duplicitní značku param pro {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateParamTag_Title"> <source>XML comment has a duplicate param tag</source> <target state="translated">Komentář XML má duplicitní značku param.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamTag"> <source>XML comment has a param tag for '{0}', but there is no parameter by that name</source> <target state="translated">Komentář XML má značku param pro {0}, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamTag_Title"> <source>XML comment has a param tag, but there is no parameter by that name</source> <target state="translated">Komentář XML má značku param, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamRefTag"> <source>XML comment on '{1}' has a paramref tag for '{0}', but there is no parameter by that name</source> <target state="translated">Komentář XML u {1} má značku paramref pro {0}, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamRefTag_Title"> <source>XML comment has a paramref tag, but there is no parameter by that name</source> <target state="translated">Komentář XML má značku paramref, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingParamTag"> <source>Parameter '{0}' has no matching param tag in the XML comment for '{1}' (but other parameters do)</source> <target state="translated">Parametr {0} nemá žádnou odpovídající značku param v komentáři XML pro {1} (ale jiné parametry ano).</target> <note /> </trans-unit> <trans-unit id="WRN_MissingParamTag_Title"> <source>Parameter has no matching param tag in the XML comment (but other parameters do)</source> <target state="translated">Parametr nemá odpovídající značku param v komentáři XML (na rozdíl od jiných parametrů).</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRef"> <source>XML comment has cref attribute '{0}' that could not be resolved</source> <target state="translated">Komentář XML má atribut cref {0}, který se nedal vyřešit.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRef_Title"> <source>XML comment has cref attribute that could not be resolved</source> <target state="translated">Komentář XML má atribut cref, který se nedal vyřešit.</target> <note /> </trans-unit> <trans-unit id="ERR_BadStackAllocExpr"> <source>A stackalloc expression requires [] after type</source> <target state="translated">Výraz stackalloc vyžaduje, aby za typem byly závorky [].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLineNumber"> <source>The line number specified for #line directive is missing or invalid</source> <target state="translated">Číslo řádku zadané v direktivě #line se nenašlo nebo je neplatné.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPPFile"> <source>Quoted file name, single-line comment or end-of-line expected</source> <target state="translated">Očekával se citovaný název souboru, jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedPPFile"> <source>Quoted file name expected</source> <target state="translated">Očekával se citovaný název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts"> <source>#r is only allowed in scripts</source> <target state="translated">#r je povolený jenom ve skriptech.</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachMissingMember"> <source>foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefParamType"> <source>Invalid type for parameter {0} in XML comment cref attribute: '{1}'</source> <target state="translated">Neplatný typ pro parametr {0} v atributu cref komentáře XML: {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefParamType_Title"> <source>Invalid type for parameter in XML comment cref attribute</source> <target state="translated">Neplatný typ pro parametr v atributu cref komentáře XML.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefReturnType"> <source>Invalid return type in XML comment cref attribute</source> <target state="translated">Neplatný typ vrácené hodnoty v atributu cref komentáře XML</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefReturnType_Title"> <source>Invalid return type in XML comment cref attribute</source> <target state="translated">Neplatný typ vrácené hodnoty v atributu cref komentáře XML</target> <note /> </trans-unit> <trans-unit id="ERR_BadWin32Res"> <source>Error reading Win32 resources -- {0}</source> <target state="translated">Chyba při čtení prostředků Win32 -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefSyntax"> <source>XML comment has syntactically incorrect cref attribute '{0}'</source> <target state="translated">Komentář XML má syntakticky nesprávný atribut cref {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefSyntax_Title"> <source>XML comment has syntactically incorrect cref attribute</source> <target state="translated">Komentář XML má syntakticky nesprávný atribut cref.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModifierLocation"> <source>Member modifier '{0}' must precede the member type and name</source> <target state="translated">Modifikátor členu {0} musí předcházet jeho názvu a typu.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingArraySize"> <source>Array creation must have array size or array initializer</source> <target state="translated">Při vytváření pole musí být k dispozici velikost pole nebo inicializátor pole.</target> <note /> </trans-unit> <trans-unit id="WRN_UnprocessedXMLComment"> <source>XML comment is not placed on a valid language element</source> <target state="translated">Komentář XML není umístěný v platném prvku jazyka.</target> <note /> </trans-unit> <trans-unit id="WRN_UnprocessedXMLComment_Title"> <source>XML comment is not placed on a valid language element</source> <target state="translated">Komentář XML není umístěný v platném prvku jazyka.</target> <note /> </trans-unit> <trans-unit id="WRN_FailedInclude"> <source>Unable to include XML fragment '{1}' of file '{0}' -- {2}</source> <target state="translated">Nejde zahrnout fragment XML {1} ze souboru {0} -- {2}</target> <note /> </trans-unit> <trans-unit id="WRN_FailedInclude_Title"> <source>Unable to include XML fragment</source> <target state="translated">Nejde zahrnout fragment XML.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidInclude"> <source>Invalid XML include element -- {0}</source> <target state="translated">Neplatný prvek direktivy include XML -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidInclude_Title"> <source>Invalid XML include element</source> <target state="translated">Neplatný prvek direktivy include XML</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment"> <source>Missing XML comment for publicly visible type or member '{0}'</source> <target state="translated">Komentář XML pro veřejně viditelný typ nebo člen {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment_Title"> <source>Missing XML comment for publicly visible type or member</source> <target state="translated">Komentář XML pro veřejně viditelný typ nebo člen se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment_Description"> <source>The /doc compiler option was specified, but one or more constructs did not have comments.</source> <target state="translated">Byla zadaná možnost kompilátoru /doc, ale nejmíň jedna konstrukce neměla komentáře.</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseIncludeError"> <source>Badly formed XML in included comments file -- '{0}'</source> <target state="translated">Chybně vytvořený kód XML v zahrnutém souboru komentáře -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseIncludeError_Title"> <source>Badly formed XML in included comments file</source> <target state="translated">Chybně vytvořený kód XML v zahrnutém souboru komentářů</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelArgCount"> <source>Delegate '{0}' does not take {1} arguments</source> <target state="translated">Delegát {0} nepřevezme tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedSemicolon"> <source>Semicolon after method or accessor block is not valid</source> <target state="translated">Středník není platný za metodou nebo blokem přistupujícího objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodReturnCantBeRefAny"> <source>The return type of a method, delegate, or function pointer cannot be '{0}'</source> <target state="translated">Návratový typ metody, delegáta nebo ukazatele na funkci nemůže být {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CompileCancelled"> <source>Compilation cancelled by user</source> <target state="translated">Kompilaci zrušil uživatel.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodArgCantBeRefAny"> <source>Cannot make reference to variable of type '{0}'</source> <target state="translated">Nejde vytvořit odkaz na proměnnou typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocal"> <source>Cannot assign to '{0}' because it is read-only</source> <target state="translated">K položce nejde přiřadit {0}, protože je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocal"> <source>Cannot use '{0}' as a ref or out value because it is read-only</source> <target state="translated">{0} nejde použít jako hodnotu Ref nebo Out, protože je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseRequiredAttribute"> <source>The RequiredAttribute attribute is not permitted on C# types</source> <target state="translated">Atribut RequiredAttribute není povolený pro typy C#.</target> <note /> </trans-unit> <trans-unit id="ERR_NoModifiersOnAccessor"> <source>Modifiers cannot be placed on event accessor declarations</source> <target state="translated">Modifikátory nejde umístit do deklarace přistupujícího objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsCantBeWithModifier"> <source>The params parameter cannot be declared as {0}</source> <target state="translated">Parametr params nejde deklarovat jako {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnNotLValue"> <source>Cannot modify the return value of '{0}' because it is not a variable</source> <target state="translated">Vrácenou hodnotu {0} nejde změnit, protože se nejedná o proměnnou.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingCoClass"> <source>The managed coclass wrapper class '{0}' for interface '{1}' cannot be found (are you missing an assembly reference?)</source> <target state="translated">Spravovaná třída obálky coclass {0} pro rozhraní {1} se nedá najít. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousAttribute"> <source>'{0}' is ambiguous between '{1}' and '{2}'. Either use '@{0}' or explicitly include the 'Attribute' suffix.</source> <target state="needs-review-translation">{0} je nejednoznačné mezi {1} a {2}; použijte buď @{0}, nebo {0}Attribute.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgExtraRef"> <source>Argument {0} may not be passed with the '{1}' keyword</source> <target state="translated">Argument {0} se nesmí předávat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource"> <source>Option '{0}' overrides attribute '{1}' given in a source file or added module</source> <target state="translated">Možnost {0} přepíše atribut {1} zadaný ve zdrojovém souboru nebo přidaném modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource_Title"> <source>Option overrides attribute given in a source file or added module</source> <target state="translated">Možnost přepíše atribut zadaný ve zdrojovém souboru nebo přidaném modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource_Description"> <source>This warning occurs if the assembly attributes AssemblyKeyFileAttribute or AssemblyKeyNameAttribute found in source conflict with the /keyfile or /keycontainer command line option or key file name or key container specified in the Project Properties.</source> <target state="translated">Toto varování se objeví, pokud jsou atributy sestavení AssemblyKeyFileAttribute nebo AssemblyKeyNameAttribute nacházející se ve zdroji v konfliktu s parametrem příkazového řádku /keyfile nebo /keycontainer nebo názvem souboru klíče nebo kontejnerem klíčů zadaným ve vlastnostech projektu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCompatMode"> <source>Invalid option '{0}' for /langversion. Use '/langversion:?' to list supported values.</source> <target state="translated">Neplatný parametr {0} pro /langversion. Podporované hodnoty vypíšete pomocí /langversion:?.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateOnConditional"> <source>Cannot create delegate with '{0}' because it or a method it overrides has a Conditional attribute</source> <target state="translated">Delegáta s {0} nejde vytvořit, protože ten nebo metoda, kterou přepisuje, má atribut Conditional.</target> <note /> </trans-unit> <trans-unit id="ERR_CantMakeTempFile"> <source>Cannot create temporary file -- {0}</source> <target state="translated">Nedá se vytvořit dočasný soubor -- {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgRef"> <source>Argument {0} must be passed with the '{1}' keyword</source> <target state="translated">Argument {0} se musí předávat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_YieldInAnonMeth"> <source>The yield statement cannot be used inside an anonymous method or lambda expression</source> <target state="translated">Příkaz yield nejde používat uvnitř anonymních metod a výrazů lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnInIterator"> <source>Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.</source> <target state="translated">Nejde vrátit hodnotu z iterátoru. K vrácení hodnoty použijte příkaz yield return. K ukončení opakování použijte příkaz yield break.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorArgType"> <source>Iterators cannot have ref, in or out parameters</source> <target state="translated">U iterátorů nejde používat parametry ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturn"> <source>The body of '{0}' cannot be an iterator block because '{1}' is not an iterator interface type</source> <target state="translated">Tělo {0} nemůže být blok iterátoru, protože {1} není typ rozhraní iterátoru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInFinally"> <source>Cannot yield in the body of a finally clause</source> <target state="translated">V těle klauzule finally nejde používat příkaz yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInTryOfCatch"> <source>Cannot yield a value in the body of a try block with a catch clause</source> <target state="translated">V těle bloku try s klauzulí catch nejde uvést hodnotu příkazu yield.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyYield"> <source>Expression expected after yield return</source> <target state="translated">Po příkazu yield return se očekával výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonDelegateCantUse"> <source>Cannot use ref, out, or in parameter '{0}' inside an anonymous method, lambda expression, query expression, or local function</source> <target state="translated">Parametr ref, out nebo in {0} nejde použít uvnitř anonymní metody, výrazu lambda, výrazu dotazu nebo lokální funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalInnerUnsafe"> <source>Unsafe code may not appear in iterators</source> <target state="translated">Iterátory nesmí obsahovat nezabezpečený kód.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInCatch"> <source>Cannot yield a value in the body of a catch clause</source> <target state="translated">V těle klauzule catch nejde použít hodnotu získanou příkazem yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateLeave"> <source>Control cannot leave the body of an anonymous method or lambda expression</source> <target state="translated">Ovládací prvek nemůže opustit tělo anonymní metody nebo výrazu lambda.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPragma"> <source>Unrecognized #pragma directive</source> <target state="translated">Nerozpoznaná direktiva #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPragma_Title"> <source>Unrecognized #pragma directive</source> <target state="translated">Nerozpoznaná direktiva #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPWarning"> <source>Expected 'disable' or 'restore'</source> <target state="translated">Očekávala se hodnota disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPWarning_Title"> <source>Expected 'disable' or 'restore' after #pragma warning</source> <target state="translated">Po varování #pragma se očekávala hodnota disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRestoreNumber"> <source>Cannot restore warning 'CS{0}' because it was disabled globally</source> <target state="translated">Nejde obnovit varování CS{0}, protože je globálně zakázané.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRestoreNumber_Title"> <source>Cannot restore warning because it was disabled globally</source> <target state="translated">Nejde obnovit varování, protože bylo globálně zakázané.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsIterator"> <source>__arglist is not allowed in the parameter list of iterators</source> <target state="translated">Parametr __arglist není povolený v seznamu parametrů iterátorů.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeIteratorArgType"> <source>Iterators cannot have unsafe parameters or yield types</source> <target state="translated">U iterátorů nejde používat nezabezpečené parametry nebo typy yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCoClassSig"> <source>The managed coclass wrapper class signature '{0}' for interface '{1}' is not a valid class name signature</source> <target state="translated">Podpis spravované třídy obálky coclass {0} pro rozhraní {1} není platný podpis názvu třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleIEnumOfT"> <source>foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedDimsRequired"> <source>A fixed size buffer field must have the array size specifier after the field name</source> <target state="translated">Pole vyrovnávací paměti s pevnou velikostí musí mít za názvem pole uvedený specifikátor velikosti pole.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNotInStruct"> <source>Fixed size buffer fields may only be members of structs</source> <target state="translated">Pole vyrovnávací paměti pevné velikosti můžou být jenom členy struktur.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousReturnExpected"> <source>Not all code paths return a value in {0} of type '{1}'</source> <target state="translated">Ne všechny cesty kódu vracejí hodnotu v {0} typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NonECMAFeature"> <source>Feature '{0}' is not part of the standardized ISO C# language specification, and may not be accepted by other compilers</source> <target state="translated">Funkce {0} není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech</target> <note /> </trans-unit> <trans-unit id="WRN_NonECMAFeature_Title"> <source>Feature is not part of the standardized ISO C# language specification, and may not be accepted by other compilers</source> <target state="translated">Funkce není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedVerbatimLiteral"> <source>Keyword, identifier, or string expected after verbatim specifier: @</source> <target state="translated">Po specifikátoru verbatim se očekávalo klíčové slovo, identifikátor nebo řetězec: @</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonly"> <source>A readonly field cannot be used as a ref or out value (except in a constructor)</source> <target state="translated">Pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonly2"> <source>Members of readonly field '{0}' cannot be used as a ref or out value (except in a constructor)</source> <target state="translated">Členy pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru). </target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonly"> <source>A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)</source> <target state="translated">Do pole jen pro čtení není možné přiřazovat hodnoty (kromě případu, kdy je v konstruktoru nebo v metodě setter jen pro inicializaci typu, ve kterém je pole definované, nebo v inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonly2"> <source>Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)</source> <target state="translated">Členy pole jen pro čtení {0} nejde měnit (kromě případu, kdy se nacházejí uvnitř konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyNotField"> <source>Cannot use {0} '{1}' as a ref or out value because it is a readonly variable</source> <target state="translated">Nejde použít {0} {1} jako hodnotu ref nebo out, protože je to proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyNotField2"> <source>Members of {0} '{1}' cannot be used as a ref or out value because it is a readonly variable</source> <target state="translated">Členy {0} {1} nejde použít jako hodnotu ref nebo out, protože je to proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignReadonlyNotField"> <source>Cannot assign to {0} '{1}' because it is a readonly variable</source> <target state="translated">Nejde přiřadit k položce {0} {1}, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignReadonlyNotField2"> <source>Cannot assign to a member of {0} '{1}' because it is a readonly variable</source> <target state="translated">Nejde přiřadit členovi {0} {1}, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyNotField"> <source>Cannot return {0} '{1}' by writable reference because it is a readonly variable</source> <target state="translated">Nejde vrátit {0} {1} zapisovatelným odkazem, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyNotField2"> <source>Members of {0} '{1}' cannot be returned by writable reference because it is a readonly variable</source> <target state="translated">Členy {0} {1} nejde vrátit zapisovatelným odkazem, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)</source> <target state="translated">Pole statických polí jen pro čtení {0} nejde přiřadit (kromě případu, kdy se nacházejí uvnitř statického konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be used as a ref or out value (except in a static constructor)</source> <target state="translated">Pole statického pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nacházejí uvnitř statického konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocal2Cause"> <source>Cannot modify members of '{0}' because it is a '{1}'</source> <target state="translated">Členy z {0} nejde upravit, protože jde o {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocal2Cause"> <source>Cannot use fields of '{0}' as a ref or out value because it is a '{1}'</source> <target state="translated">Pole elementu {0} nejde použít jako hodnotu Ref nebo Out, protože je {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocalCause"> <source>Cannot assign to '{0}' because it is a '{1}'</source> <target state="translated">K položce nejde přiřadit {0}, protože je typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocalCause"> <source>Cannot use '{0}' as a ref or out value because it is a '{1}'</source> <target state="translated">{0} nejde použít jako hodnotu Ref nebo Out, protože je {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride"> <source>{0}. See also error CS{1}.</source> <target state="translated">{0}. Viz taky chyba CS{1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride_Title"> <source>Warning is overriding an error</source> <target state="translated">Varování přepisuje chybu.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride_Description"> <source>The compiler emits this warning when it overrides an error with a warning. For information about the problem, search for the error code mentioned.</source> <target state="translated">Kompilátor vydá toto varování, když přepíše chybu varováním. Informace o tomto problému vyhledejte podle uvedeného kódu chyby.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonMethToNonDel"> <source>Cannot convert {0} to type '{1}' because it is not a delegate type</source> <target state="translated">{0} nejde převést na typ {1}, protože to není typ delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethParams"> <source>Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types</source> <target state="translated">{0} nejde převést na typ {1}, protože typy parametrů se neshodují s typy parametrů delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethReturns"> <source>Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type</source> <target state="translated">{0} nejde převést na zamýšlený typ delegáta, protože některé z návratových typů v bloku nejsou implicitně převeditelné na návratový typ tohoto delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturnExpression"> <source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task&lt;{0}&gt;'</source> <target state="translated">Protože se jedná o asynchronní metodu, vrácený výraz musí být typu {0} a ne typu Task&lt;{0}&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAsyncAnonFuncReturns"> <source>Cannot convert async {0} to delegate type '{1}'. An async {0} may return void, Task or Task&lt;T&gt;, none of which are convertible to '{1}'.</source> <target state="translated">Asynchronní metodu {0} nejde převést na typ delegáta {1}. Asynchronní metoda {0} může vracet hodnoty typu void, Task nebo Task&lt; T&gt; , z nichž žádnou nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalFixedType"> <source>Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double</source> <target state="translated">Typ vyrovnávací paměti pevné velikosti musí být následující: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float nebo double.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedOverflow"> <source>Fixed size buffer of length {0} and type '{1}' is too big</source> <target state="translated">Vyrovnávací paměť pevné velikosti s délkou {0} a typem {1} je moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFixedArraySize"> <source>Fixed size buffers must have a length greater than zero</source> <target state="translated">Vyrovnávací paměti pevné velikosti mají délku větší než nula.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedBufferNotFixed"> <source>You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.</source> <target state="translated">Vyrovnávací paměti pevné velikosti obsažené ve volném výrazu nejde používat. Použijte příkaz fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeNotOnAccessor"> <source>Attribute '{0}' is not valid on property or event accessors. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro přistupující objekty vlastnosti nebo události. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSearchPathDir"> <source>Invalid search path '{0}' specified in '{1}' -- '{2}'</source> <target state="translated">Neplatná vyhledávací cesta {0} zadaná v {1} -- {2}</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSearchPathDir_Title"> <source>Invalid search path specified</source> <target state="translated">Byla zadaná neplatná vyhledávací cesta.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalVarArgs"> <source>__arglist is not valid in this context</source> <target state="translated">Klíčové slovo __arglist není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalParams"> <source>params is not valid in this context</source> <target state="translated">Klíčové slovo params není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModifiersOnNamespace"> <source>A namespace declaration cannot have modifiers or attributes</source> <target state="translated">Deklarace oboru názvů nemůže mít modifikátory ani atributy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPlatformType"> <source>Invalid option '{0}' for /platform; must be anycpu, x86, Itanium, arm, arm64 or x64</source> <target state="translated">Neplatná možnost {0} pro /platform. Musí být anycpu, x86, Itanium, arm, arm64 nebo x64.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisStructNotInAnonMeth"> <source>Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.</source> <target state="translated">Anonymní metody, výrazy lambda, výrazy dotazu a místní funkce uvnitř struktur nemají přístup ke členům instance this. Jako náhradu zkopírujte objekt this do lokální proměnné vně anonymní metody, výrazu lambda, výrazu dotazu nebo místní funkce a použijte tuto lokální proměnnou.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIDisp"> <source>'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'.</source> <target state="translated">{0}: Typ použitý v příkazu using musí být implicitně převeditelný na System.IDisposable.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamRef"> <source>Parameter {0} must be declared with the '{1}' keyword</source> <target state="translated">Parametr {0} se musí deklarovat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamExtraRef"> <source>Parameter {0} should not be declared with the '{1}' keyword</source> <target state="translated">Parametr {0} by se neměl deklarovat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamType"> <source>Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}'</source> <target state="translated">Parametr {0} se deklaruje jako typ {1}{2}, ale mělo by jít o {3}{4}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExternIdentifier"> <source>Invalid extern alias for '/reference'; '{0}' is not a valid identifier</source> <target state="translated">Neplatný externí alias pro parametr /reference; {0} je neplatný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasMissingFile"> <source>Invalid reference alias option: '{0}=' -- missing filename</source> <target state="translated">Neplatný parametr aliasu odkazu: {0}= – nenašel se název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalExternAlias"> <source>You cannot redefine the global extern alias</source> <target state="translated">Nejde předefinovat globální externí alias.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingTypeInSource"> <source>Reference to type '{0}' claims it is defined in this assembly, but it is not defined in source or any added modules</source> <target state="translated">Odkaz na typ {0} se deklaruje jako definovaný v tomto sestavení, ale není definovaný ve zdroji ani v žádných přidaných modulech.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingTypeInAssembly"> <source>Reference to type '{0}' claims it is defined in '{1}', but it could not be found</source> <target state="translated">Odkaz na typ {0} se deklaruje jako definovaný v rámci {1}, ale nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes"> <source>The predefined type '{0}' is defined in multiple assemblies in the global alias; using definition from '{1}'</source> <target state="translated">Předdefinovaný typ {0} je definovaný ve více sestaveních v globálním aliasu; použije se definice z {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes_Title"> <source>Predefined type is defined in multiple assemblies in the global alias</source> <target state="translated">Předdefinovaný typ je definovaný ve více sestaveních v globálním aliasu.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes_Description"> <source>This error occurs when a predefined system type such as System.Int32 is found in two assemblies. One way this can happen is if you are referencing mscorlib or System.Runtime.dll from two different places, such as trying to run two versions of the .NET Framework side-by-side.</source> <target state="translated">K této chybě dojde, když se předdefinovaný systémový typ, jako je System.Int32, nachází ve dvou sestaveních. Jedna z možností, jak se to může stát, je, že odkazujete na mscorlib nebo System.Runtime.dll, ze dvou různých míst, například při pokusu spustit dvě verze .NET Framework vedle sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalCantBeFixedAndHoisted"> <source>Local '{0}' or its members cannot have their address taken and be used inside an anonymous method or lambda expression</source> <target state="translated">Adresu místní proměnné {0} ani jejích členů nejde vzít a použít uvnitř anonymní metody nebo lambda výrazu.</target> <note /> </trans-unit> <trans-unit id="WRN_TooManyLinesForDebugger"> <source>Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect</source> <target state="translated">U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné.</target> <note /> </trans-unit> <trans-unit id="WRN_TooManyLinesForDebugger_Title"> <source>Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect</source> <target state="translated">U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethNoParams"> <source>Cannot convert anonymous method block without a parameter list to delegate type '{0}' because it has one or more out parameters</source> <target state="translated">Blok anonymní metody bez seznamu parametrů nejde převést na typ delegáta {0}, protože má nejmíň jeden parametr out.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnNonAttributeClass"> <source>Attribute '{0}' is only valid on methods or attribute classes</source> <target state="translated">Atribut {0} je platný jenom pro metody nebo třídy atributů.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField"> <source>Accessing a member on '{0}' may cause a runtime exception because it is a field of a marshal-by-reference class</source> <target state="translated">Přístup ke členovi na {0} může způsobit výjimku za běhu, protože se jedná o pole třídy marshal-by-reference.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField_Title"> <source>Accessing a member on a field of a marshal-by-reference class may cause a runtime exception</source> <target state="translated">Přístup ke členovi v poli třídy marshal-by-reference může způsobit běhovou výjimku.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField_Description"> <source>This warning occurs when you try to call a method, property, or indexer on a member of a class that derives from MarshalByRefObject, and the member is a value type. Objects that inherit from MarshalByRefObject are typically intended to be marshaled by reference across an application domain. If any code ever attempts to directly access the value-type member of such an object across an application domain, a runtime exception will occur. To resolve the warning, first copy the member into a local variable and call the method on that variable.</source> <target state="translated">Toto varování se vyskytne, když se pokusíte volat metodu, vlastnost nebo indexer u členu třídy, která se odvozuje z objektu MarshalByRefObject, a tento člen je typu hodnota. Objekty, které dědí z objektu MarshalByRefObject, jsou obvykle zamýšlené tak, že se budou zařazovat podle odkazů v aplikační doméně. Pokud se nějaký kód někdy pokusí o přímý přístup ke členu typu hodnota takového objektu někde v aplikační doméně, dojde k výjimce běhu modulu runtime. Pokud chcete vyřešit toto varování, zkopírujte nejdřív člen do místní proměnné a pak u ní vyvolejte uvedenou metodu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber"> <source>'{0}' is not a valid warning number</source> <target state="translated">{0} není platné číslo upozornění.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber_Title"> <source>Not a valid warning number</source> <target state="translated">Není platné číslo varování.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber_Description"> <source>A number that was passed to the #pragma warning preprocessor directive was not a valid warning number. Verify that the number represents a warning, not an error.</source> <target state="translated">Číslo, které bylo předané do direktivy preprocesoru varování #pragma, nepředstavovalo platné číslo varování. Ověřte, že číslo představuje varování, ne chybu.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidNumber"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidNumber_Title"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="WRN_FileNameTooLong"> <source>Invalid filename specified for preprocessor directive. Filename is too long or not a valid filename.</source> <target state="translated">V direktivě preprocesoru je uvedený neplatný název souboru. Název souboru je moc dlouhý nebo se nejedná o platný název souboru.</target> <note /> </trans-unit> <trans-unit id="WRN_FileNameTooLong_Title"> <source>Invalid filename specified for preprocessor directive</source> <target state="translated">Byl zadaný neplatný název souboru pro direktivu preprocesoru.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPChecksum"> <source>Invalid #pragma checksum syntax; should be #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..."</source> <target state="translated">Syntaxe #pragma checksum není platná. Správná syntaxe: #pragma checksum "název_souboru" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..."</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPChecksum_Title"> <source>Invalid #pragma checksum syntax</source> <target state="translated">Neplatná syntaxe kontrolního součtu #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_EndOfPPLineExpected"> <source>Single-line comment or end-of-line expected</source> <target state="translated">Očekával se jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="WRN_EndOfPPLineExpected_Title"> <source>Single-line comment or end-of-line expected after #pragma directive</source> <target state="translated">Po direktivě #pragma se očekával jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingChecksum"> <source>Different checksum values given for '{0}'</source> <target state="translated">Pro {0} jsou zadané různé hodnoty kontrolního součtu.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingChecksum_Title"> <source>Different #pragma checksum values given</source> <target state="translated">Jsou zadané různé hodnoty kontrolního součtu direktivy #pragma.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Title"> <source>Assembly reference is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Description"> <source>This warning indicates that an attribute, such as InternalsVisibleToAttribute, was not specified correctly.</source> <target state="translated">Toto varování indikuje, že některý atribut, třeba InternalsVisibleToAttribute, nebyl zadaný správně.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin"> <source>Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy</source> <target state="translated">Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin_Title"> <source>Assuming assembly reference matches identity</source> <target state="translated">Předpokládá se, že odkaz na sestavení odpovídá identitě.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin_Description"> <source>The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly.</source> <target state="translated">Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev"> <source>Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy</source> <target state="translated">Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev_Title"> <source>Assuming assembly reference matches identity</source> <target state="translated">Předpokládá se, že odkaz na sestavení odpovídá identitě.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev_Description"> <source>The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly.</source> <target state="translated">Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImport"> <source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source> <target state="translated">Naimportovalo se víc sestavení s ekvivalentní identitou: {0} a {1}. Odeberte jeden z duplicitních odkazů.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImportSimple"> <source>An assembly with the same simple name '{0}' has already been imported. Try removing one of the references (e.g. '{1}') or sign them to enable side-by-side.</source> <target state="translated">Už se naimportovalo sestavení se stejným jednoduchým názvem {0}. Zkuste odebrat jeden z odkazů (např. {1}) nebo je podepište, aby mohly fungovat vedle sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblyMatchBadVersion"> <source>Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}'</source> <target state="translated">Sestavení {0} s identitou {1} používá {2} s vyšší verzí, než jakou má odkazované sestavení {3} s identitou {4}.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNeedsLvalue"> <source>Fixed size buffers can only be accessed through locals or fields</source> <target state="translated">K vyrovnávacím pamětem s pevnou velikostí jde získat přístup jenom prostřednictvím lokálních proměnných nebo polí.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateTypeParamTag"> <source>XML comment has a duplicate typeparam tag for '{0}'</source> <target state="translated">Komentář XML má duplicitní značku typeparam pro {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateTypeParamTag_Title"> <source>XML comment has a duplicate typeparam tag</source> <target state="translated">Komentář XML má duplicitní značku typeparam.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamTag"> <source>XML comment has a typeparam tag for '{0}', but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparam pro {0}, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamTag_Title"> <source>XML comment has a typeparam tag, but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparam, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamRefTag"> <source>XML comment on '{1}' has a typeparamref tag for '{0}', but there is no type parameter by that name</source> <target state="translated">Komentář XML u {1} má značku typeparamref pro {0}, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamRefTag_Title"> <source>XML comment has a typeparamref tag, but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparamref, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingTypeParamTag"> <source>Type parameter '{0}' has no matching typeparam tag in the XML comment on '{1}' (but other type parameters do)</source> <target state="translated">Parametr typu {0} nemá žádnou odpovídající značku typeparam v komentáři XML na {1} (ale jiné parametry typu ano).</target> <note /> </trans-unit> <trans-unit id="WRN_MissingTypeParamTag_Title"> <source>Type parameter has no matching typeparam tag in the XML comment (but other type parameters do)</source> <target state="translated">Parametr typu nemá odpovídající značku typeparam v komentáři XML (na rozdíl od jiných parametrů typu).</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeTypeOnOverride"> <source>'{0}': type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoNotUseFixedBufferAttr"> <source>Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead.</source> <target state="translated">Nepoužívejte atribut System.Runtime.CompilerServices.FixedBuffer. Místo něj použijte modifikátor pole fixed.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToSelf"> <source>Assignment made to same variable; did you mean to assign something else?</source> <target state="translated">Přiřazení proběhlo u stejné proměnné. Měli jste v úmyslu jiné přiřazení?</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToSelf_Title"> <source>Assignment made to same variable</source> <target state="translated">Přiřazení provedené u stejné proměnné</target> <note /> </trans-unit> <trans-unit id="WRN_ComparisonToSelf"> <source>Comparison made to same variable; did you mean to compare something else?</source> <target state="translated">Porovnání proběhlo u stejné proměnné. Měli jste v úmyslu jiné porovnání?</target> <note /> </trans-unit> <trans-unit id="WRN_ComparisonToSelf_Title"> <source>Comparison made to same variable</source> <target state="translated">Porovnání provedené u stejné proměnné</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenWin32Res"> <source>Error opening Win32 resource file '{0}' -- '{1}'</source> <target state="translated">Chyba při otevírání souboru prostředků Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="WRN_DotOnDefault"> <source>Expression will always cause a System.NullReferenceException because the default value of '{0}' is null</source> <target state="translated">Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota {0} je null.</target> <note /> </trans-unit> <trans-unit id="WRN_DotOnDefault_Title"> <source>Expression will always cause a System.NullReferenceException because the type's default value is null</source> <target state="translated">Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota pro typ je null.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMultipleInheritance"> <source>Class '{0}' cannot have multiple base classes: '{1}' and '{2}'</source> <target state="translated">Třída {0} nemůže mít víc základních tříd: {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseClassMustBeFirst"> <source>Base class '{0}' must come before any interfaces</source> <target state="translated">Základní třída {0} musí předcházet všem rozhraním.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefTypeVar"> <source>XML comment has cref attribute '{0}' that refers to a type parameter</source> <target state="translated">Komentář XML má atribut cref {0}, který odkazuje na parametr typu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefTypeVar_Title"> <source>XML comment has cref attribute that refers to a type parameter</source> <target state="translated">Komentář XML má atribut cref, který odkazuje na parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadArgs"> <source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source> <target state="translated">Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo nesmí být zadaná verze, jazykové prostředí, token veřejného klíče ani architektura procesoru.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblySNReq"> <source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source> <target state="translated">Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo musí být u podepsaných sestavení se silným názvem uvedený veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateOnNullable"> <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable&lt;T&gt;'</source> <target state="translated">Nejde vytvořit vazbu delegáta s {0}, protože je členem struktury System.Nullable&lt;T&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCtorArgCount"> <source>'{0}' does not contain a constructor that takes {1} arguments</source> <target state="translated">{0} neobsahuje konstruktor, který přebírá tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalAttributesNotFirst"> <source>Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations</source> <target state="translated">Atributy sestavení a modulu musí předcházet přede všemi ostatními prvky definovanými v souboru s výjimkou klauzulí using a deklarací externích aliasů.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionExpected"> <source>Expected expression</source> <target state="translated">Očekával se výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSubsystemVersion"> <source>Invalid version {0} for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise</source> <target state="translated">Neplatná verze {0} pro /subsystemversion. Verze musí být 6.02 nebo vyšší pro ARM nebo AppContainerExe a 4.00 nebo vyšší v ostatních případech.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropMethodWithBody"> <source>Embedded interop method '{0}' contains a body.</source> <target state="translated">Vložená metoda spolupráce {0} obsahuje tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_BadWarningLevel"> <source>Warning level must be zero or greater</source> <target state="translated">Úroveň upozornění musí být nula nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDebugType"> <source>Invalid option '{0}' for /debug; must be 'portable', 'embedded', 'full' or 'pdbonly'</source> <target state="translated">Neplatný parametr {0} pro /debug; musí být portable, embedded, full nebo pdbonly.</target> <note /> </trans-unit> <trans-unit id="ERR_BadResourceVis"> <source>Invalid option '{0}'; Resource visibility must be either 'public' or 'private'</source> <target state="translated">Neplatná možnost {0}. Viditelnost zdroje musí být public nebo private.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueTypeMustMatch"> <source>The type of the argument to the DefaultParameterValue attribute must match the parameter type</source> <target state="translated">Typ argumentu atributu DefaultParameterValue musí odpovídat typu parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueBadValueType"> <source>Argument of type '{0}' is not applicable for the DefaultParameterValue attribute</source> <target state="translated">Argument typu {0} není použitelný pro atribut DefaultParameterValue.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberAlreadyInitialized"> <source>Duplicate initialization of member '{0}'</source> <target state="translated">Duplicitní inicializace členu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_MemberCannotBeInitialized"> <source>Member '{0}' cannot be initialized. It is not a field or property.</source> <target state="translated">Člen {0} nejde inicializovat. Nejedná se o pole ani vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticMemberInObjectInitializer"> <source>Static field or property '{0}' cannot be assigned in an object initializer</source> <target state="translated">Statické pole nebo vlastnost {0} se nedá přiřadit k inicializátoru objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_ReadonlyValueTypeInObjectInitializer"> <source>Members of readonly field '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type</source> <target state="translated">Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTypePropertyInObjectInitializer"> <source>Members of property '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type</source> <target state="translated">Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeTypeInObjectCreation"> <source>Unsafe type '{0}' cannot be used in object creation</source> <target state="translated">K vytvoření objektu nejde použít nezabezpečený typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyElementInitializer"> <source>Element initializer cannot be empty</source> <target state="translated">Inicializátor prvku nemůže být prázdný.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerAddHasWrongSignature"> <source>The best overloaded method match for '{0}' has wrong signature for the initializer element. The initializable Add must be an accessible instance method.</source> <target state="translated">Odpovídající optimální přetěžovaná metoda pro {0} má nesprávný podpis prvku inicializátoru. Jako inicializovatelná metoda Add se musí používat dostupná instanční metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_CollectionInitRequiresIEnumerable"> <source>Cannot initialize type '{0}' with a collection initializer because it does not implement 'System.Collections.IEnumerable'</source> <target state="translated">Nejde inicializovat typ {0} pomocí inicializátoru kolekce, protože neimplementuje System.Collections.IEnumerable.</target> <note /> </trans-unit> <trans-unit id="ERR_CantSetWin32Manifest"> <source>Error reading Win32 manifest file '{0}' -- '{1}'</source> <target state="translated">Chyba při čtení souboru manifestu Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="WRN_CantHaveManifestForModule"> <source>Ignoring /win32manifest for module because it only applies to assemblies</source> <target state="translated">Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením.</target> <note /> </trans-unit> <trans-unit id="WRN_CantHaveManifestForModule_Title"> <source>Ignoring /win32manifest for module because it only applies to assemblies</source> <target state="translated">Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInstanceArgType"> <source>'{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' requires a receiver of type '{3}'</source> <target state="translated">{0} neobsahuje definici pro {1} a přetížení optimální metody rozšíření {2} vyžaduje přijímač typu {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryDuplicateRangeVariable"> <source>The range variable '{0}' has already been declared</source> <target state="translated">Proměnná rozsahu {0} je už deklarovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableOverrides"> <source>The range variable '{0}' conflicts with a previous declaration of '{0}'</source> <target state="translated">Proměnná rozsahu {0} je v konfliktu s předchozí deklarací {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableAssignedBadValue"> <source>Cannot assign {0} to a range variable</source> <target state="translated">{0} nejde přiřadit k proměnné rozsahu.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProviderCastable"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Consider explicitly specifying the type of the range variable '{2}'.</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Zvažte možnost explicitního určení typu proměnné rozsahu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProviderStandard"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Are you missing required assembly references or a using directive for 'System.Linq'?</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Nechybí odkazy na požadovaná sestavení nebo direktiva using pro System.Linq?</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProvider"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOuterKey"> <source>The name '{0}' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.</source> <target state="translated">Název {0} není v oboru levé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryInnerKey"> <source>The name '{0}' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.</source> <target state="translated">Název {0} není v oboru pravé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOutRefRangeVariable"> <source>Cannot pass the range variable '{0}' as an out or ref parameter</source> <target state="translated">Proměnnou rozsahu {0} nejde předat jako vnější nebo odkazovaný parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryMultipleProviders"> <source>Multiple implementations of the query pattern were found for source type '{0}'. Ambiguous call to '{1}'.</source> <target state="translated">Našlo se víc implementací vzorku dotazu pro typ zdroje {0}. Nejednoznačné volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailedMulti"> <source>The type of one of the expressions in the {0} clause is incorrect. Type inference failed in the call to '{1}'.</source> <target state="translated">Typ jednoho z výrazů v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailed"> <source>The type of the expression in the {0} clause is incorrect. Type inference failed in the call to '{1}'.</source> <target state="translated">Typ výrazu v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailedSelectMany"> <source>An expression of type '{0}' is not allowed in a subsequent from clause in a query expression with source type '{1}'. Type inference failed in the call to '{2}'.</source> <target state="translated">Není povolené použití výrazu typu {0} v následné klauzuli from ve výrazu dotazu s typem zdroje {1}. Nepovedlo se odvození typu při volání funkce {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsPointerOp"> <source>An expression tree may not contain an unsafe pointer operation</source> <target state="translated">Strom výrazů nesmí obsahovat nezabezpečenou operaci s ukazatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAnonymousMethod"> <source>An expression tree may not contain an anonymous method expression</source> <target state="translated">Strom výrazů nesmí obsahovat výraz anonymní metody.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousMethodToExpressionTree"> <source>An anonymous method expression cannot be converted to an expression tree</source> <target state="translated">Výraz anonymní metody nejde převést na strom výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableReadOnly"> <source>Range variable '{0}' cannot be assigned to -- it is read only</source> <target state="translated">K proměnné rozsahu {0} nejde přiřazovat – je jenom pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableSameAsTypeParam"> <source>The range variable '{0}' cannot have the same name as a method type parameter</source> <target state="translated">Proměnná rozsahu {0} nesmí mít stejný název jako parametr typu metody.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarNotFoundRangeVariable"> <source>The contextual keyword 'var' cannot be used in a range variable declaration</source> <target state="translated">V deklaraci proměnné rozsahu nejde použít kontextové klíčové slovo var.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgTypesForCollectionAdd"> <source>The best overloaded Add method '{0}' for the collection initializer has some invalid arguments</source> <target state="translated">Některé argumenty optimální přetěžované metody Add {0} pro inicializátor kolekce jsou neplatné.</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefParameterInExpressionTree"> <source>An expression tree lambda may not contain a ref, in or out parameter</source> <target state="translated">Strom výrazu lambda nesmí obsahovat parametr ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_VarArgsInExpressionTree"> <source>An expression tree lambda may not contain a method with variable arguments</source> <target state="translated">Strom výrazu lambda nesmí obsahovat metodu s proměnnými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_MemGroupInExpressionTree"> <source>An expression tree lambda may not contain a method group</source> <target state="translated">Strom výrazu lambda nesmí obsahovat skupinu metod.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerAddHasParamModifiers"> <source>The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.</source> <target state="translated">Optimální nalezenou přetěžovanou metodu {0} pro element inicializátoru kolekce nejde použít. Metody Add inicializátoru kolekce nemůžou mít parametry Ref nebo Out.</target> <note /> </trans-unit> <trans-unit id="ERR_NonInvocableMemberCalled"> <source>Non-invocable member '{0}' cannot be used like a method.</source> <target state="translated">Nevyvolatelného člena {0} nejde použít jako metodu.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches"> <source>Member '{0}' implements interface member '{1}' in type '{2}'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called.</source> <target state="translated">Člen {0} implementuje člen rozhraní {1} v typu {2}. Za běhu existuje pro tohoto člena rozhraní víc shod. Volaná metoda závisí na konkrétní implementaci.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches_Title"> <source>Member implements interface member with multiple matches at run-time</source> <target state="translated">Člen za běhu implementuje člena rozhraní s více shodami.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches_Description"> <source>This warning can be generated when two interface methods are differentiated only by whether a particular parameter is marked with ref or with out. It is best to change your code to avoid this warning because it is not obvious or guaranteed which method is called at runtime. Although C# distinguishes between out and ref, the CLR sees them as the same. When deciding which method implements the interface, the CLR just picks one. Give the compiler some way to differentiate the methods. For example, you can give them different names or provide an additional parameter on one of them.</source> <target state="translated">Toto varování se může vygenerovat, když jsou dvě metody rozhraní odlišené jenom tím, že určitý parametr je označený jednou jako ref a podruhé jako out. Doporučuje se kód změnit tak, aby k tomuto varování nedocházelo, protože není úplně jasné nebo zaručené, která metoda se má za běhu vyvolat. Ačkoli C# rozlišuje mezi out a ref, pro CLR je to totéž. Při rozhodování, která metoda má implementovat rozhraní, modul CLR prostě jednu vybere. Poskytněte kompilátoru nějaký způsob, jak metody rozlišit. Můžete například zadat různé názvy nebo k jedné z nich přidat parametr navíc.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeOverrideMatches"> <source>Member '{1}' overrides '{0}'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime.</source> <target state="translated">Člen {1} přepisuje člen {0}. Za běhu existuje více kandidátů na přepis. Volaná metoda závisí na konkrétní implementaci. Použijte prosím novější modul runtime.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeOverrideMatches_Title"> <source>Member overrides base member with multiple override candidates at run-time</source> <target state="translated">Člen za běhu přepíše základního člena s více kandidáty na přepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectOrCollectionInitializerWithDelegateCreation"> <source>Object and collection initializer expressions may not be applied to a delegate creation expression</source> <target state="translated">Výrazy inicializátoru objektu a kolekce nejde použít na výraz vytvářející delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidConstantDeclarationType"> <source>'{0}' is of type '{1}'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.</source> <target state="translated">{0} je typu {1}. V deklaraci konstanty musí být uvedený typ sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, výčtový typ nebo typ odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_FileNotFound"> <source>Source file '{0}' could not be found.</source> <target state="translated">Zdrojový soubor {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded"> <source>Source file '{0}' specified multiple times</source> <target state="translated">Zdrojový soubor {0} je zadaný několikrát.</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded_Title"> <source>Source file specified multiple times</source> <target state="translated">Zdrojový soubor je zadaný několikrát.</target> <note /> </trans-unit> <trans-unit id="ERR_NoFileSpec"> <source>Missing file specification for '{0}' option</source> <target state="translated">Pro možnost {0} chybí specifikace souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsString"> <source>Command-line syntax error: Missing '{0}' for '{1}' option</source> <target state="translated">Chyba syntaxe příkazového řádku: Nenašla se hodnota {0} pro možnost {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitch"> <source>Unrecognized option: '{0}'</source> <target state="translated">Nerozpoznaná možnost: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_NoSources"> <source>No source files specified.</source> <target state="translated">Nejsou zadané žádné zdrojové soubory.</target> <note /> </trans-unit> <trans-unit id="WRN_NoSources_Title"> <source>No source files specified</source> <target state="translated">Nejsou zadané žádné zdrojové soubory.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSingleScript"> <source>Expected a script (.csx file) but none specified</source> <target state="translated">Očekával se skript (soubor .csx), žádný ale není zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_OpenResponseFile"> <source>Error opening response file '{0}'</source> <target state="translated">Chyba při otevírání souboru odpovědí {0}</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenFileWrite"> <source>Cannot open '{0}' for writing -- '{1}'</source> <target state="translated">{0} se nedá otevřít pro zápis -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBaseNumber"> <source>Invalid image base number '{0}'</source> <target state="translated">Neplatné základní číslo obrázku {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryFile"> <source>'{0}' is a binary file instead of a text file</source> <target state="translated">{0} je binární, ne textový soubor.</target> <note /> </trans-unit> <trans-unit id="FTL_BadCodepage"> <source>Code page '{0}' is invalid or not installed</source> <target state="translated">Znaková stránka {0} je neplatná nebo není nainstalovaná.</target> <note /> </trans-unit> <trans-unit id="FTL_BadChecksumAlgorithm"> <source>Algorithm '{0}' is not supported</source> <target state="translated">Algoritmus {0} není podporovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMainOnDLL"> <source>Cannot specify /main if building a module or library</source> <target state="translated">Při vytváření modulu nebo knihovny nejde použít přepínač /main.</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidTarget"> <source>Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'</source> <target state="translated">Neplatný typ cíle pro parametr /target: Je nutné použít možnost exe, winexe, library nebo module.</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigNotOnCommandLine"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí.</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigNotOnCommandLine_Title"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFileAlignment"> <source>Invalid file section alignment '{0}'</source> <target state="translated">Neplatný argument výběru souboru {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOutputName"> <source>Invalid output name: {0}</source> <target state="translated">Neplatný název výstupu: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInformationFormat"> <source>Invalid debug information format: {0}</source> <target state="translated">Neplatný formát informací o ladění: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_LegacyObjectIdSyntax"> <source>'id#' syntax is no longer supported. Use '$id' instead.</source> <target state="translated">'Syntaxe id# už není podporovaná. Použijte místo ní syntaxi $id.</target> <note /> </trans-unit> <trans-unit id="WRN_DefineIdentifierRequired"> <source>Invalid name for a preprocessing symbol; '{0}' is not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; {0} není platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="WRN_DefineIdentifierRequired_Title"> <source>Invalid name for a preprocessing symbol; not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; neplatný identifikátor</target> <note /> </trans-unit> <trans-unit id="FTL_OutputFileExists"> <source>Cannot create short filename '{0}' when a long filename with the same short filename already exists</source> <target state="translated">Nejde vytvořit krátký název souboru {0}, protože už existuje dlouhý název souboru se stejným krátkým názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_OneAliasPerReference"> <source>A /reference option that declares an extern alias can only have one filename. To specify multiple aliases or filenames, use multiple /reference options.</source> <target state="translated">Parametr /reference deklarující externí alias může mít jenom jeden název souboru. Pokud chcete zadat víc aliasů nebo názvů souborů, použijte více parametrů /reference.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsNumber"> <source>Command-line syntax error: Missing ':&lt;number&gt;' for '{0}' option</source> <target state="translated">Chyba syntaxe příkazového řádku: Nenašla se hodnota :&lt;číslo&gt; parametru {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingDebugSwitch"> <source>The /pdb option requires that the /debug option also be used</source> <target state="translated">Možnost /pdb vyžaduje taky použití možnosti /debug .</target> <note /> </trans-unit> <trans-unit id="ERR_ComRefCallInExpressionTree"> <source>An expression tree lambda may not contain a COM call with ref omitted on arguments</source> <target state="translated">Strom výrazu lambda nesmí obsahovat volání COM, které v argumentech vynechává parametr Ref.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatForGuidForOption"> <source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source> <target state="translated">Chyba syntaxe příkazového řádku: Neplatný formát GUID {0} pro možnost {1}</target> <note /> </trans-unit> <trans-unit id="ERR_MissingGuidForOption"> <source>Command-line syntax error: Missing Guid for option '{1}'</source> <target state="translated">Chyba syntaxe příkazového řádku: Chybí GUID pro možnost {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoVarArgs"> <source>Methods with variable arguments are not CLS-compliant</source> <target state="translated">Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoVarArgs_Title"> <source>Methods with variable arguments are not CLS-compliant</source> <target state="translated">Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadArgType"> <source>Argument type '{0}' is not CLS-compliant</source> <target state="translated">Typ argumentu {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadArgType_Title"> <source>Argument type is not CLS-compliant</source> <target state="translated">Typ argumentu není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadReturnType"> <source>Return type of '{0}' is not CLS-compliant</source> <target state="translated">Typ vrácené hodnoty {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadReturnType_Title"> <source>Return type is not CLS-compliant</source> <target state="translated">Návratový typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType"> <source>Type of '{0}' is not CLS-compliant</source> <target state="translated">Typ {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType_Title"> <source>Type is not CLS-compliant</source> <target state="translated">Typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType_Description"> <source>A public, protected, or protected internal variable must be of a type that is compliant with the Common Language Specification (CLS).</source> <target state="translated">Veřejná, chráněná nebo interně chráněná proměnná musí být typu, který je kompatibilní se specifikací CLS (Common Language Specification).</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifierCase"> <source>Identifier '{0}' differing only in case is not CLS-compliant</source> <target state="translated">Identifikátor {0} lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifierCase_Title"> <source>Identifier differing only in case is not CLS-compliant</source> <target state="translated">Identifikátor lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadRefOut"> <source>Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda {0} lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadRefOut_Title"> <source>Overloaded method differing only in ref or out, or in array rank, is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed"> <source>Overloaded method '{0}' differing only by unnamed array types is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda {0} lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed_Title"> <source>Overloaded method differing only by unnamed array types is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed_Description"> <source>This error occurs if you have an overloaded method that takes a jagged array and the only difference between the method signatures is the element type of the array. To avoid this error, consider using a rectangular array rather than a jagged array; use an additional parameter to disambiguate the function call; rename one or more of the overloaded methods; or, if CLS Compliance is not needed, remove the CLSCompliantAttribute attribute.</source> <target state="translated">Tato chyba se objeví, pokud máte přetěžovanou metodu, která přebírá vícenásobné pole, a jediný rozdíl mezi signaturami metody je typ elementu tohoto pole. Aby nedošlo k této chybě, zvažte použití pravoúhlého pole namísto vícenásobného, použijte další parametr, aby volání této funkce bylo jednoznačné, přejmenujte nejmíň jednu přetěžovanou metodu nebo (pokud kompatibilita s CLS není nutná) odeberte atribut CLSCompliantAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifier"> <source>Identifier '{0}' is not CLS-compliant</source> <target state="translated">Identifikátor {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifier_Title"> <source>Identifier is not CLS-compliant</source> <target state="translated">Identifikátor není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase"> <source>'{0}': base type '{1}' is not CLS-compliant</source> <target state="translated">{0}: Základní typ {1} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase_Title"> <source>Base type is not CLS-compliant</source> <target state="translated">Základní typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase_Description"> <source>A base type was marked as not having to be compliant with the Common Language Specification (CLS) in an assembly that was marked as being CLS compliant. Either remove the attribute that specifies the assembly is CLS compliant or remove the attribute that indicates the type is not CLS compliant.</source> <target state="translated">Základní typ byl označený tak, že nemusí být kompatibilní se specifikací CLS (Common Language Specification) v sestavení, které bylo označené jako kompatibilní s CLS. Buď odeberte atribut, který sestavení určuje jako kompatibilní s CLS, nebo odeberte atribut, který označuje typ jako nekompatibilní s CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterfaceMember"> <source>'{0}': CLS-compliant interfaces must have only CLS-compliant members</source> <target state="translated">{0}: Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterfaceMember_Title"> <source>CLS-compliant interfaces must have only CLS-compliant members</source> <target state="translated">Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoAbstractMembers"> <source>'{0}': only CLS-compliant members can be abstract</source> <target state="translated">{0}: Jenom členy kompatibilní se specifikací CLS můžou být abstraktní.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoAbstractMembers_Title"> <source>Only CLS-compliant members can be abstract</source> <target state="translated">Jenom členy kompatibilní se specifikací CLS můžou být abstraktní.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules"> <source>You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking</source> <target state="translated">Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules_Title"> <source>You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking</source> <target state="translated">Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ModuleMissingCLS"> <source>Added modules must be marked with the CLSCompliant attribute to match the assembly</source> <target state="translated">Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ModuleMissingCLS_Title"> <source>Added modules must be marked with the CLSCompliant attribute to match the assembly</source> <target state="translated">Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS"> <source>'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute</source> <target state="translated">{0} nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS_Title"> <source>Type or member cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute</source> <target state="translated">Typ nebo člen nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadAttributeType"> <source>'{0}' has no accessible constructors which use only CLS-compliant types</source> <target state="translated">{0} nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadAttributeType_Title"> <source>Type has no accessible constructors which use only CLS-compliant types</source> <target state="translated">Typ nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ArrayArgumentToAttribute"> <source>Arrays as attribute arguments is not CLS-compliant</source> <target state="translated">Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ArrayArgumentToAttribute_Title"> <source>Arrays as attribute arguments is not CLS-compliant</source> <target state="translated">Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules2"> <source>You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly</source> <target state="translated">Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules2_Title"> <source>You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly</source> <target state="translated">Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_IllegalTrueInFalse"> <source>'{0}' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type '{1}'</source> <target state="translated">{0} nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu {1}, který není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_IllegalTrueInFalse_Title"> <source>Type cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type</source> <target state="translated">Typ nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu, který není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnPrivateType"> <source>CLS compliance checking will not be performed on '{0}' because it is not visible from outside this assembly</source> <target state="translated">Pro prvek {0} se neprovede kontrola kompatibility se specifikací CLS, protože není viditelný mimo toto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnPrivateType_Title"> <source>CLS compliance checking will not be performed because it is not visible from outside this assembly</source> <target state="translated">Kontrola kompatibility se specifikací CLS se neprovede, protože není viditelná zvnějšku tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS2"> <source>'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute</source> <target state="translated">{0} nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS2_Title"> <source>Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute</source> <target state="translated">Typ nebo člen nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnParam"> <source>CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead.</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u parametrů. Použijte jej místo toho u metody.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnParam_Title"> <source>CLSCompliant attribute has no meaning when applied to parameters</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u parametrů.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnReturn"> <source>CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead.</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u typů vrácených hodnot. Použijte jej místo toho u metody.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnReturn_Title"> <source>CLSCompliant attribute has no meaning when applied to return types</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u návratových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadTypeVar"> <source>Constraint type '{0}' is not CLS-compliant</source> <target state="translated">Typ omezení {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadTypeVar_Title"> <source>Constraint type is not CLS-compliant</source> <target state="translated">Typ omezení není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_VolatileField"> <source>CLS-compliant field '{0}' cannot be volatile</source> <target state="translated">Pole kompatibilní se specifikací CLS {0} nemůže být typu volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_VolatileField_Title"> <source>CLS-compliant field cannot be volatile</source> <target state="translated">Pole kompatibilní se specifikací CLS nemůže být typu volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterface"> <source>'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant</source> <target state="translated">{0} není kompatibilní se specifikací CLS, protože základní rozhraní {1} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterface_Title"> <source>Type is not CLS-compliant because base interface is not CLS-compliant</source> <target state="translated">Typ není kompatibilní se specifikací CLS, protože základní rozhraní není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArg"> <source>'await' requires that the type {0} have a suitable 'GetAwaiter' method</source> <target state="translated">'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArgIntrinsic"> <source>Cannot await '{0}'</source> <target state="translated">Operátor await nejde použít pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaiterPattern"> <source>'await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable 'IsCompleted', 'OnCompleted', and 'GetResult' members, and implement 'INotifyCompletion' or 'ICriticalNotifyCompletion'</source> <target state="translated">'Operátor await vyžaduje, aby návratový typ {0} metody {1}.GetAwaiter() měl odpovídající členy IsCompleted, OnCompleted a GetResult a implementoval rozhraní INotifyCompletion nebo ICriticalNotifyCompletion.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArg_NeedSystem"> <source>'await' requires that the type '{0}' have a suitable 'GetAwaiter' method. Are you missing a using directive for 'System'?</source> <target state="translated">'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter. Chybí vám direktiva using pro položku System?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArgVoidCall"> <source>Cannot await 'void'</source> <target state="translated">Operátor await nejde použít pro void.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitAsIdentifier"> <source>'await' cannot be used as an identifier within an async method or lambda expression</source> <target state="translated">'Operátor Await nejde použít jako identifikátor v asynchronní metodě nebo výrazu lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesntImplementAwaitInterface"> <source>'{0}' does not implement '{1}'</source> <target state="translated">{0} neimplementuje {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TaskRetNoObjectRequired"> <source>Since '{0}' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task&lt;T&gt;'?</source> <target state="translated">Protože metoda {0} je asynchronní a její návratový typ je Task, za klíčovým slovem return nesmí následovat objektový výraz. Měli jste v úmyslu vrátit hodnotu typu Task&lt;T&gt;?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturn"> <source>The return type of an async method must be void, Task, Task&lt;T&gt;, a task-like type, IAsyncEnumerable&lt;T&gt;, or IAsyncEnumerator&lt;T&gt;</source> <target state="translated">Návratový typ asynchronní metody musí být void, Task, Task&lt;T&gt;, typ podobný úloze, IAsyncEnumerable&lt;T&gt; nebo IAsyncEnumerator&lt;T&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReturnVoid"> <source>Cannot return an expression of type 'void'</source> <target state="translated">Nejde vrátit výraz typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsAsync"> <source>__arglist is not allowed in the parameter list of async methods</source> <target state="translated">Klíčové slovo __arglist není povolené v seznamu parametrů asynchronních metod.</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefTypeAndAwait"> <source>'await' cannot be used in an expression containing the type '{0}'</source> <target state="translated">'Operátor await nejde použít ve výrazu, který obsahuje typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeAsyncArgType"> <source>Async methods cannot have unsafe parameters or return types</source> <target state="translated">Asynchronní metody nemůžou mít návratové typy nebo parametry, které nejsou bezpečné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncArgType"> <source>Async methods cannot have ref, in or out parameters</source> <target state="translated">Asynchronní metody nemůžou mít parametry ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsync"> <source>The 'await' operator can only be used when contained within a method or lambda expression marked with the 'async' modifier</source> <target state="translated">Operátor await jde použít, jenom pokud je obsažen v metodě nebo výrazu lambda označeném pomocí modifikátoru async.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsyncLambda"> <source>The 'await' operator can only be used within an async {0}. Consider marking this {0} with the 'async' modifier.</source> <target state="translated">Operátor await jde použít jenom v asynchronní metodě {0}. Zvažte označení této metody modifikátorem async.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsyncMethod"> <source>The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task&lt;{0}&gt;'.</source> <target state="translated">Operátor await jde použít jenom v asynchronních metodách. Zvažte označení této metody modifikátorem async a změnu jejího návratového typu na Task&lt;{0}&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutVoidAsyncMethod"> <source>The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.</source> <target state="translated">Operátor await jde použít jenom v asynchronní metodě. Zvažte označení této metody pomocí modifikátoru async a změnu jejího návratového typu na Task.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInFinally"> <source>Cannot await in the body of a finally clause</source> <target state="translated">Nejde použít operátor await v těle klauzule finally.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInCatch"> <source>Cannot await in a catch clause</source> <target state="translated">Operátor await nejde použít v klauzuli catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInCatchFilter"> <source>Cannot await in the filter expression of a catch clause</source> <target state="translated">Nejde použít operátor await ve výrazu filtru klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInLock"> <source>Cannot await in the body of a lock statement</source> <target state="translated">Operátor await nejde použít v příkazu lock.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInStaticVariableInitializer"> <source>The 'await' operator cannot be used in a static script variable initializer.</source> <target state="translated">Operátor await nejde použít v inicializátoru proměnné statického skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitInUnsafeContext"> <source>Cannot await in an unsafe context</source> <target state="translated">Operátor await nejde použít v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncLacksBody"> <source>The 'async' modifier can only be used in methods that have a body.</source> <target state="translated">Modifikátor async se dá použít jenom v metodách, které mají tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecialByRefLocal"> <source>Parameters or locals of type '{0}' cannot be declared in async methods or async lambda expressions.</source> <target state="translated">Parametry nebo lokální proměnné typu {0} nemůžou být deklarované v asynchronních metodách nebo asynchronních výrazech lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecialByRefIterator"> <source>foreach statement cannot operate on enumerators of type '{0}' in async or iterator methods because '{0}' is a ref struct.</source> <target state="translated">Výraz foreach nejde použít na enumerátorech typu {0} v asynchronních metodách nebo metodách iterátoru, protože {0} je struktura REF.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync"> <source>Security attribute '{0}' cannot be applied to an Async method.</source> <target state="translated">Atribut zabezpečení {0} nejde použít pro metodu Async.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct"> <source>Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source> <target state="translated">Asynchronní metody nejsou povolené v rozhraní, třídě nebo struktuře, které mají atribut SecurityCritical nebo SecuritySafeCritical.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInQuery"> <source>The 'await' operator may only be used in a query expression within the first collection expression of the initial 'from' clause or within the collection expression of a 'join' clause</source> <target state="translated">Operátor await jde použít jenom ve výrazu dotazu v rámci první kolekce výrazu počáteční klauzule from nebo v rámci výrazu kolekce klauzule join.</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits"> <source>This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.</source> <target state="translated">V této asynchronní metodě chybí operátory await a spustí se synchronně. Zvažte použití operátoru await pro čekání na neblokující volání rozhraní API nebo vykonání činnosti vázané na procesor ve vlákně na pozadí pomocí výrazu await Task.Run(...).</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits_Title"> <source>Async method lacks 'await' operators and will run synchronously</source> <target state="translated">V této asynchronní metodě chybí operátory await a spustí se synchronně.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression"> <source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.</source> <target state="translated">Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání. Zvažte použití operátoru await na výsledek volání.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Title"> <source>Because this call is not awaited, execution of the current method continues before the call is completed</source> <target state="translated">Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Description"> <source>The current method calls an async method that returns a Task or a Task&lt;TResult&gt; and doesn't apply the await operator to the result. The call to the async method starts an asynchronous task. However, because no await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't what you expect. Usually other aspects of the calling method depend on the results of the call or, minimally, the called method is expected to complete before you return from the method that contains the call. An equally important issue is what happens to exceptions that are raised in the called async method. An exception that's raised in a method that returns a Task or Task&lt;TResult&gt; is stored in the returned task. If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions. In that case, you can suppress the warning by assigning the task result of the call to a variable.</source> <target state="translated">Aktuální metoda volá asynchronní metodu, která vrací úlohu nebo úlohu&lt;TResult&gt; a ve výsledku nepoužije operátor await. Volání asynchronní metody spustí asynchronní úlohu. Vzhledem k tomu, že se ale nepoužil žádný operátor await, bude program pokračovat bez čekání na dokončení úlohy. Ve většině případů se nejedná o chování, které byste očekávali. Ostatní aspekty volání metody obvykle závisí na výsledcích volání nebo se aspoň očekává, že se volaná metoda dokončí před vaším návratem z metody obsahující volání. Stejně důležité je i to, co se stane s výjimkami, ke kterým dojde ve volané asynchronní metodě. Výjimka, ke které dojde v metodě vracející úlohu nebo úlohu&lt;TResult&gt;, se uloží do vrácené úlohy. Pokud úlohu neočekáváte nebo explicitně výjimky nekontrolujete, dojde ke ztrátě výjimky. Pokud úlohu očekáváte, dojde k výjimce znovu. Nejvhodnějším postupem je volání vždycky očekávat. Potlačení upozornění zvažte jenom v případě, když určitě nechcete čekat na dokončení asynchronního volání a jste si jistí, že volaná metoda nevyvolá žádné výjimky. V takovém případě můžete upozornění potlačit tak, že výsledek úlohy volání přidružíte proměnné.</target> <note /> </trans-unit> <trans-unit id="ERR_SynchronizedAsyncMethod"> <source>'MethodImplOptions.Synchronized' cannot be applied to an async method</source> <target state="translated">'Možnost MethodImplOptions.Synchronized nejde použít pro asynchronní metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerLineNumberParam"> <source>CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerLineNumberAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerFilePathParam"> <source>CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerFilePathAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerMemberNameParam"> <source>CallerMemberNameAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerMemberNameAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerLineNumberParamWithoutDefaultValue"> <source>The CallerLineNumberAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerLineNumberAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerFilePathParamWithoutDefaultValue"> <source>The CallerFilePathAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerFilePathAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerMemberNameParamWithoutDefaultValue"> <source>The CallerMemberNameAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerMemberNameAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberParamForUnconsumedLocation"> <source>The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerLineNumberAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberParamForUnconsumedLocation_Title"> <source>The CallerLineNumberAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerLineNumberAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathParamForUnconsumedLocation"> <source>The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerFilePathAttribute použitý u parametru {0} nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathParamForUnconsumedLocation_Title"> <source>The CallerFilePathAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerFilePathAttribute nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNameParamForUnconsumedLocation"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNameParamForUnconsumedLocation_Title"> <source>The CallerMemberNameAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_NoEntryPoint"> <source>Program does not contain a static 'Main' method suitable for an entry point</source> <target state="translated">Program neobsahuje statickou metodu Main vhodnou pro vstupní bod.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerIncorrectLength"> <source>An array initializer of length '{0}' is expected</source> <target state="translated">Očekává se inicializátor pole s délkou {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerExpected"> <source>A nested array initializer is expected</source> <target state="translated">Očekává se inicializátor vnořeného pole.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalVarianceSyntax"> <source>Invalid variance modifier. Only interface and delegate type parameters can be specified as variant.</source> <target state="translated">Modifikátor odchylky je neplatný. Jako variant můžou být určeny jenom parametry typu delegát nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedAliasedName"> <source>Unexpected use of an aliased name</source> <target state="translated">Neočekávané použití názvu v aliasu</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedGenericName"> <source>Unexpected use of a generic name</source> <target state="translated">Neočekávané použití obecného názvu</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedUnboundGenericName"> <source>Unexpected use of an unbound generic name</source> <target state="translated">Neočekávané použití odvázaného obecného názvu</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalStatement"> <source>Expressions and statements can only occur in a method body</source> <target state="translated">Výrazy a příkazy se můžou vyskytnout jenom v těle metody.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentForArray"> <source>An array access may not have a named argument specifier</source> <target state="translated">Přístup k poli nemůže mít specifikátor pojmenovaného argumentu.</target> <note /> </trans-unit> <trans-unit id="ERR_NotYetImplementedInRoslyn"> <source>This language feature ('{0}') is not yet implemented.</source> <target state="translated">Tato jazyková funkce ({0}) zatím není implementovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueNotAllowed"> <source>Default values are not valid in this context.</source> <target state="translated">Výchozí hodnoty nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenIcon"> <source>Error opening icon file {0} -- {1}</source> <target state="translated">Chyba při otevírání souboru ikony {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenWin32Manifest"> <source>Error opening Win32 manifest file {0} -- {1}</source> <target state="translated">Chyba při otevírání souboru manifestu Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorBuildingWin32Resources"> <source>Error building Win32 resources -- {0}</source> <target state="translated">Chyba při sestavování prostředků Win32 -- {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueBeforeRequiredValue"> <source>Optional parameters must appear after all required parameters</source> <target state="translated">Volitelné parametry musí následovat po všech povinných parametrech</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplCollisionOnRefOut"> <source>Cannot inherit interface '{0}' with the specified type parameters because it causes method '{1}' to contain overloads which differ only on ref and out</source> <target state="translated">Nejde dědit rozhraní {0} se zadanými parametry typu, protože to způsobuje, že metoda {1} obsahuje víc přetížení, která se liší jen deklaracemi ref a out.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongTypeParamsVariance"> <source>Partial declarations of '{0}' must have the same type parameter names and variance modifiers in the same order</source> <target state="translated">Částečné deklarace {0} musí obsahovat názvy parametrů stejného typu a modifikátory odchylek ve stejném pořadí.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedVariance"> <source>Invalid variance: The type parameter '{1}' must be {3} valid on '{0}'. '{1}' is {2}.</source> <target state="translated">Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}. {1} je {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromDynamic"> <source>'{0}': cannot derive from the dynamic type</source> <target state="translated">{0}: Nejde odvozovat z dynamického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromConstructedDynamic"> <source>'{0}': cannot implement a dynamic interface '{1}'</source> <target state="translated">{0}: Nemůže implementovat dynamické rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicTypeAsBound"> <source>Constraint cannot be the dynamic type</source> <target state="translated">Omezení nemůže být dynamický typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructedDynamicTypeAsBound"> <source>Constraint cannot be a dynamic type '{0}'</source> <target state="translated">Omezení nemůže být dynamický typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicRequiredTypesMissing"> <source>One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?</source> <target state="translated">Jeden nebo více typů požadovaných pro kompilaci dynamického výrazu nejde najít. Nechybí odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataNameTooLong"> <source>Name '{0}' exceeds the maximum length allowed in metadata.</source> <target state="translated">Název {0} překračuje maximální délku povolenou v metadatech.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributesNotAllowed"> <source>Attributes are not valid in this context.</source> <target state="translated">Atributy nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternAliasNotAllowed"> <source>'extern alias' is not valid in this context</source> <target state="translated">'Alias extern není v tomto kontextu platný.</target> <note /> </trans-unit> <trans-unit id="WRN_IsDynamicIsConfusing"> <source>Using '{0}' to test compatibility with '{1}' is essentially identical to testing compatibility with '{2}' and will succeed for all non-null values</source> <target state="translated">Použití operátoru {0} pro testování kompatibility s typem {1} je v podstatě totožné s testováním kompatibility s typem {2} a bude úspěšné pro všechny hodnoty, které nejsou null.</target> <note /> </trans-unit> <trans-unit id="WRN_IsDynamicIsConfusing_Title"> <source>Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object'</source> <target state="translated">Použití operátoru is pro testování kompatibility s typem dynamic je v podstatě totožné s testováním kompatibility s typem Object.</target> <note /> </trans-unit> <trans-unit id="ERR_YieldNotAllowedInScript"> <source>Cannot use 'yield' in top-level script code</source> <target state="translated">Příkaz yield se nedá použít v kódu skriptu nejvyšší úrovně.</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAllowedInScript"> <source>Cannot declare namespace in script code</source> <target state="translated">Obor názvů se nedá deklarovat v kódu skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalAttributesNotAllowed"> <source>Assembly and module attributes are not allowed in this context</source> <target state="translated">Atributy sestavení a modulů nejsou v tomto kontextu povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDelegateType"> <source>Delegate '{0}' has no invoke method or an invoke method with a return type or parameter types that are not supported.</source> <target state="translated">Delegát {0} nemá žádnou metodu invoke nebo má jeho metoda invoke nepodporovaný návratový typ nebo typy parametrů.</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored"> <source>The entry point of the program is global code; ignoring '{0}' entry point.</source> <target state="translated">Vstupním bodem programu je globální kód. Vstupní bod {0} se ignoruje.</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored_Title"> <source>The entry point of the program is global code; ignoring entry point</source> <target state="translated">Vstupním bodem programu je globální kód. Vstupní bod se ignoruje</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisEventType"> <source>Inconsistent accessibility: event type '{1}' is less accessible than event '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ události {1} je míň dostupný než událost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgument"> <source>Named argument specifications must appear after all fixed arguments have been specified. Please use language version {0} or greater to allow non-trailing named arguments.</source> <target state="translated">Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů. Pokud chcete povolit pojmenované argumenty, které nejsou na konci, použijte prosím jazyk verze {0} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation"> <source>Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation.</source> <target state="translated">Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů v dynamickém vyvolání.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedArgument"> <source>The best overload for '{0}' does not have a parameter named '{1}'</source> <target state="translated">Nejlepší přetížení pro {0} neobsahuje parametr s názvem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedArgumentForDelegateInvoke"> <source>The delegate '{0}' does not have a parameter named '{1}'</source> <target state="translated">Delegát {0} neobsahuje parametr s názvem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedArgument"> <source>Named argument '{0}' cannot be specified multiple times</source> <target state="translated">Pojmenovaný argument {0} nejde zadat víckrát.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentUsedInPositional"> <source>Named argument '{0}' specifies a parameter for which a positional argument has already been given</source> <target state="translated">Pojmenovaný argument {0} určuje parametr, pro který už byl poskytnut poziční argument.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNonTrailingNamedArgument"> <source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source> <target state="translated">Pojmenovaný argument {0} se používá mimo pozici, je ale následovaný nepojmenovaným argumentem.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueUsedWithAttributes"> <source>Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute</source> <target state="translated">Nejde zadat výchozí hodnotu parametru v kombinaci s atributy DefaultParameterAttribute nebo OptionalAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueMustBeConstant"> <source>Default parameter value for '{0}' must be a compile-time constant</source> <target state="translated">Výchozí hodnota parametru pro {0} musí být konstanta definovaná při kompilaci.</target> <note /> </trans-unit> <trans-unit id="ERR_RefOutDefaultValue"> <source>A ref or out parameter cannot have a default value</source> <target state="translated">Parametr Ref nebo Uut nemůže mít výchozí hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForExtensionParameter"> <source>Cannot specify a default value for the 'this' parameter</source> <target state="translated">Nejde zadat výchozí hodnotu pro parametr this.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForParamsParameter"> <source>Cannot specify a default value for a parameter array</source> <target state="translated">Nejde zadat výchozí hodnotu pro pole parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForDefaultParam"> <source>A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}'</source> <target state="translated">Hodnotu typu {0} nejde použít jako výchozí parametr, protože neexistují žádné standardní převody na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForNubDefaultParam"> <source>A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type</source> <target state="translated">Hodnotu typu {0} nejde použít jako výchozí hodnotu parametru {1} s možnou hodnotou null, protože {0} není jednoduchý typ.</target> <note /> </trans-unit> <trans-unit id="ERR_NotNullRefDefaultParameter"> <source>'{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null</source> <target state="translated">{0} je typu {1}. Výchozí hodnotu parametru s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultValueForUnconsumedLocation"> <source>The default value specified for parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">Výchozí hodnota zadaná pro parametr {0} nebude mít žádný efekt, protože platí pro člen, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultValueForUnconsumedLocation_Title"> <source>The default value specified will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">Určená výchozí hodnota nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyFileFailure"> <source>Error signing output with public key from file '{0}' -- {1}</source> <target state="translated">Chyba při podepisování výstupu pomocí veřejného klíče ze souboru {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyContainerFailure"> <source>Error signing output with public key from container '{0}' -- {1}</source> <target state="translated">Chyba při podepisování výstupu pomocí veřejného klíče z kontejneru {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicTypeof"> <source>The typeof operator cannot be used on the dynamic type</source> <target state="translated">Operátor typeof nejde použít na tento dynamický typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsDynamicOperation"> <source>An expression tree may not contain a dynamic operation</source> <target state="translated">Strom výrazu nemůže obsahovat dynamickou operaci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncExpressionTree"> <source>Async lambda expressions cannot be converted to expression trees</source> <target state="translated">Asynchronní výrazy lambda nejde převést na stromy výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicAttributeMissing"> <source>Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">Nejde definovat třídu nebo člen, který používá typ dynamic, protože se nedá najít typ {0} požadovaný kompilátorem. Nechybí odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_CannotPassNullForFriendAssembly"> <source>Cannot pass null for friend assembly name</source> <target state="translated">Jako název sestavení typu Friend nejde předat hodnotu Null.</target> <note /> </trans-unit> <trans-unit id="ERR_SignButNoPrivateKey"> <source>Key file '{0}' is missing the private key needed for signing</source> <target state="translated">V souboru klíče {0} chybí privátní klíč potřebný k podepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignButNoKey"> <source>Public signing was specified and requires a public key, but no public key was specified.</source> <target state="translated">Byl určený veřejný podpis, který vyžaduje veřejný klíč, nebyl ale zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNetModule"> <source>Public signing is not supported for netmodules.</source> <target state="translated">Veřejné podepisování netmodulů se nepodporuje.</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey_Title"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat"> <source>The specified version string does not conform to the required format - major[.minor[.build[.revision]]]</source> <target state="translated">Zadaný řetězec verze není v souladu s požadovaným formátem – hlavní_verze[.dílčí_verze[.build[.revize]]].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormatDeterministic"> <source>The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation</source> <target state="translated">Zadaný řetězec verze obsahuje zástupné znaky, které nejsou kompatibilní s determinismem. Odeberte zástupné znaky z řetězce verze nebo pro tuto kompilaci zakažte determinismus.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat2"> <source>The specified version string does not conform to the required format - major.minor.build.revision (without wildcards)</source> <target state="translated">Zadaný řetězec verze není v souladu s požadovaným formátem – hlavní_verze.dílčí_verze.build.revize (bez zástupných znaků).</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">Zadaný řetězec verze není v souladu s doporučeným formátem – hlavní_verze.dílčí_verze.build.revize.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat_Title"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">Zadaný řetězec verze není v souladu s doporučeným formátem – hlavní_verze.dílčí_verze.build.revize.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCultureForExe"> <source>Executables cannot be satellite assemblies; culture should always be empty</source> <target state="translated">Spustitelné soubory nemůžou být satelitními sestaveními; jazyková verze by vždy měla být prázdná.</target> <note /> </trans-unit> <trans-unit id="ERR_NoCorrespondingArgument"> <source>There is no argument given that corresponds to the required formal parameter '{0}' of '{1}'</source> <target state="translated">Není dán žádný argument, který by odpovídal požadovanému formálnímu parametru {0} v {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch"> <source>The command line switch '{0}' is not yet implemented and was ignored.</source> <target state="translated">Přepínač příkazového řádku {0} ještě není implementovaný, a tak se ignoroval.</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch_Title"> <source>Command line switch is not yet implemented</source> <target state="translated">Přepínač příkazového řádku zatím není implementovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleEmitFailure"> <source>Failed to emit module '{0}': {1}</source> <target state="translated">Nepovedlo se vygenerovat modul {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_FixedLocalInLambda"> <source>Cannot use fixed local '{0}' inside an anonymous method, lambda expression, or query expression</source> <target state="translated">Pevnou lokální proměnnou {0} nejde použít v anonymní metodě, lambda výrazu nebo výrazu dotazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsNamedArgument"> <source>An expression tree may not contain a named argument specification</source> <target state="translated">Strom výrazu nemůže obsahovat specifikaci pojmenovaného argumentu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsOptionalArgument"> <source>An expression tree may not contain a call or invocation that uses optional arguments</source> <target state="translated">Strom výrazu nemůže obsahovat volání, které používá nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsIndexedProperty"> <source>An expression tree may not contain an indexed property</source> <target state="translated">Strom výrazu nemůže obsahovat indexovanou vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedPropertyRequiresParams"> <source>Indexed property '{0}' has non-optional arguments which must be provided</source> <target state="translated">Indexovaná vlastnost {0} má argumenty, které nejsou nepovinné a je třeba je zadat.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedPropertyMustHaveAllOptionalParams"> <source>Indexed property '{0}' must have all arguments optional</source> <target state="translated">Indexovaná vlastnost {0} musí mít všechny argumenty volitelné.</target> <note /> </trans-unit> <trans-unit id="ERR_SpecialByRefInLambda"> <source>Instance of type '{0}' cannot be used inside a nested function, query expression, iterator block or async method</source> <target state="translated">Instance typu {0} nelze použít uvnitř vnořené funkce, výrazu dotazu, bloku iterátoru nebo asynchronní metody.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeMissingAction"> <source>First argument to a security attribute must be a valid SecurityAction</source> <target state="translated">První argument atributu zabezpečení musí být platný SecurityAction.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidAction"> <source>Security attribute '{0}' has an invalid SecurityAction value '{1}'</source> <target state="translated">Atribut zabezpečení {0} má neplatnou hodnotu SecurityAction {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionAssembly"> <source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod"> <source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u typu nebo metody.</target> <note /> </trans-unit> <trans-unit id="ERR_PrincipalPermissionInvalidAction"> <source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atribut PrincipalPermission.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotValidInExpressionTree"> <source>An expression tree may not contain '{0}'</source> <target state="translated">Strom výrazu nesmí obsahovat {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeInvalidFile"> <source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute</source> <target state="translated">Nejde vyřešit cestu k souboru {0} zadanému pro pojmenovaný argument {1} pro atribut PermissionSet.</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeFileReadError"> <source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'</source> <target state="translated">Chyba při čtení souboru {0} zadaného pro pojmenovaný argument {1} pro atribut PermissionSet: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalSingleTypeNameNotFoundFwd"> <source>The type name '{0}' could not be found in the global namespace. This type has been forwarded to assembly '{1}' Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nepovedlo najít v globálním oboru názvů. Tento typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInNSFwd"> <source>The type name '{0}' could not be found in the namespace '{1}'. This type has been forwarded to assembly '{2}' Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nepovedlo najít v oboru názvů {1}. Tento typ se předal do sestavení {2}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleTypeNameNotFoundFwd"> <source>The type name '{0}' could not be found. This type has been forwarded to assembly '{1}'. Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nenašel. Typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblySpecifiedForLinkAndRef"> <source>Assemblies '{0}' and '{1}' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references.</source> <target state="translated">Sestavení {0} a {1} odkazují na stejná metadata, ale jenom v jednom případě je to propojený odkaz (zadaný s možností /link). Zvažte odebrání jednoho z odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAdd"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete.</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAdd_Title"> <source>The best overloaded Add method for the collection initializer element is obsolete</source> <target state="translated">Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAddStr"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1}</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1}</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAddStr_Title"> <source>The best overloaded Add method for the collection initializer element is obsolete</source> <target state="translated">Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="ERR_DeprecatedCollectionInitAddStr"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1}</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidTarget"> <source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source> <target state="translated">Atribut zabezpečení {0} není platný u tohoto typu deklarace. Atributy zabezpečení jsou platné jenom u deklarací sestavení, typu a metody.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArg"> <source>Cannot use an expression of type '{0}' as an argument to a dynamically dispatched operation.</source> <target state="translated">Nejde použít výraz typu {0} jako argument pro dynamicky volanou operaci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArgLambda"> <source>Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.</source> <target state="translated">Výraz lambda nejde použít jako argument dynamicky volané operace, aniž byste ho nejprve použili na typy delegát nebo strom výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArgMemgrp"> <source>Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?</source> <target state="translated">Skupinu metod nejde použít jako argument v dynamicky volané operaci. Měli jste v úmyslu tuto metodu vyvolat?</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBase"> <source>The call to method '{0}' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.</source> <target state="translated">Volání do metody {0} je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte přetypování dynamických argumentů nebo eliminaci základního přístupu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicQuery"> <source>Query expressions over source type 'dynamic' or with a join sequence of type 'dynamic' are not allowed</source> <target state="translated">Výrazy dotazů se zdrojovým typem dynamic nebo se spojenou sekvencí typu dynamic nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBaseIndexer"> <source>The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.</source> <target state="translated">Přístup indexeru je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte použití dynamických argumentů nebo eliminaci základního přístupu.</target> <note /> </trans-unit> <trans-unit id="WRN_DynamicDispatchToConditionalMethod"> <source>The dynamically dispatched call to method '{0}' may fail at runtime because one or more applicable overloads are conditional methods.</source> <target state="translated">Dynamicky volané volání do metody {0} se za běhu nemusí zdařit, protože nejmíň jedno použitelné přetížení je podmíněná metoda.</target> <note /> </trans-unit> <trans-unit id="WRN_DynamicDispatchToConditionalMethod_Title"> <source>Dynamically dispatched call may fail at runtime because one or more applicable overloads are conditional methods</source> <target state="translated">Dynamicky volané volání může za běhu selhat, protože nejmíň jedno použitelné přetížení představuje podmíněnou metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgTypeDynamicExtension"> <source>'{0}' has no applicable method named '{1}' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.</source> <target state="translated">{0} nemá žádnou použitelnou metodu s názvem {1}, ale zřejmě má metodu rozšíření s tímto názvem. Metody rozšíření se nedají volat dynamicky. Zvažte použití dynamických argumentů nebo volání metody rozšíření bez syntaxe metody rozšíření.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerMemberName"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerMemberName_Title"> <source>The CallerMemberNameAttribute will have no effect; it is overridden by the CallerFilePathAttribute</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerMemberName"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerMemberName_Title"> <source>The CallerMemberNameAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerFilePath"> <source>The CallerFilePathAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="translated">CallerFilePathAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerFilePath_Title"> <source>The CallerFilePathAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="translated">CallerFilePathAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDynamicCondition"> <source>Expression must be implicitly convertible to Boolean or its type '{0}' must define operator '{1}'.</source> <target state="translated">Výraz musí být implicitně převeditelný na logickou hodnotu nebo její typ {0} musí definovat operátor {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MixingWinRTEventWithRegular"> <source>'{0}' cannot implement '{1}' because '{2}' is a Windows Runtime event and '{3}' is a regular .NET event.</source> <target state="translated">{0} nemůže implementovat {1}, protože {2} je událost Windows Runtimu a {3} je normální událost .NET.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope1"> <source>Call System.IDisposable.Dispose() on allocated instance of {0} before all references to it are out of scope.</source> <target state="translated">Vyvolejte System.IDisposable.Dispose() na přidělenou instanci {0} dřív, než budou všechny odkazy na ni mimo obor.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope1_Title"> <source>Call System.IDisposable.Dispose() on allocated instance before all references to it are out of scope</source> <target state="translated">Vyvolejte System.IDisposable.Dispose() u přidělené instance, než budou všechny odkazy na ni mimo rozsah.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope2"> <source>Allocated instance of {0} is not disposed along all exception paths. Call System.IDisposable.Dispose() before all references to it are out of scope.</source> <target state="translated">Přidělená instance {0} se neuvolní v průběhu všech cest výjimky. Vyvolejte System.IDisposable.Dispose() dřív, než budou všechny odkazy na ni mimo obor.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope2_Title"> <source>Allocated instance is not disposed along all exception paths</source> <target state="translated">Přidělená instance není uvolněná v průběhu všech cest výjimek.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2202_DoNotDisposeObjectsMultipleTimes"> <source>Object '{0}' can be disposed more than once.</source> <target state="translated">Objekt {0} se dá uvolnit víc než jednou.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2202_DoNotDisposeObjectsMultipleTimes_Title"> <source>Object can be disposed more than once</source> <target state="translated">Objekt se dá uvolnit víc než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_NewCoClassOnLink"> <source>Interop type '{0}' cannot be embedded. Use the applicable interface instead.</source> <target state="translated">Typ spolupráce {0} nemůže být vložený. Místo něho použijte použitelné rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIANestedType"> <source>Type '{0}' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože je vnořeným typem. Zvažte nastavení vlastnosti Vložit typy spolupráce na false.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericsUsedInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a generic argument. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má obecný argument. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropStructContainsMethods"> <source>Embedded interop struct '{0}' can contain only public instance fields.</source> <target state="translated">Vložená struktura spolupráce {0} může obsahovat jenom veřejné položky instance.</target> <note /> </trans-unit> <trans-unit id="ERR_WinRtEventPassedByRef"> <source>A Windows Runtime event may not be passed as an out or ref parameter.</source> <target state="translated">Událost Windows Runtimu se nesmí předat jako parametr out nebo ref.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingMethodOnSourceInterface"> <source>Source interface '{0}' is missing method '{1}' which is required to embed event '{2}'.</source> <target state="translated">Zdrojovému rozhraní {0} chybí metoda {1}, která se vyžaduje pro vložení události {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingSourceInterface"> <source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source> <target state="translated">Rozhraní {0} má neplatné zdrojové rozhraní, které se vyžaduje pro vložení události {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropTypeMissingAttribute"> <source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source> <target state="translated">Typ spolupráce {0} nemůže být vložený, protože postrádá požadovaný atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAssemblyMissingAttribute"> <source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source> <target state="translated">Nejde vložit typy spolupráce pro sestavení {0}, protože postrádá atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAssemblyMissingAttributes"> <source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source> <target state="translated">Nejde vložit typy spolupráce ze sestavení {0}, protože postrádá buď atribut {1}, nebo atribut {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropTypesWithSameNameAndGuid"> <source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Nejde vložit typ spolupráce {0} nalezený v sestavení {1} i {2}. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalTypeNameClash"> <source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Vložení typu spolupráce {0} ze sestavení {1} způsobí konflikt názvů v aktuálním sestavení. Zvažte nastavení vlastnosti Vložit typy spolupráce na false.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA"> <source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly created by assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source> <target state="translated">Vytvořil se odkaz na vložené sestavení vzájemné spolupráce {0}, protože existuje nepřímý odkaz na toto sestavení ze sestavení {1}. Zvažte změnu vlastnosti Vložit typy vzájemné spolupráce u obou sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA_Title"> <source>A reference was created to embedded interop assembly because of an indirect assembly reference</source> <target state="translated">Byl vytvořený odkaz na vložené definiční sestavení z důvodu nepřímého odkazu na toto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA_Description"> <source>You have added a reference to an assembly using /link (Embed Interop Types property set to True). This instructs the compiler to embed interop type information from that assembly. However, the compiler cannot embed interop type information from that assembly because another assembly that you have referenced also references that assembly using /reference (Embed Interop Types property set to False). To embed interop type information for both assemblies, use /link for references to each assembly (set the Embed Interop Types property to True). To remove the warning, you can use /reference instead (set the Embed Interop Types property to False). In this case, a primary interop assembly (PIA) provides interop type information.</source> <target state="translated">Přidali jste odkaz na sestavení pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). Tím se kompilátoru dává instrukce, aby vložil informace o typech spolupráce z tohoto sestavení. Kompilátor ale nemůže tyto informace z tohoto sestavení vložit, protože jiné sestavení, na které jste nastavili odkaz, odkazuje taky na toto sestavení, a to pomocí parametru /reference (vlastnost Přibalit definované typy nastavená na False). Pokud chcete vložit informace o typech spolupráce pro obě sestavení, odkazujte na každé z nich pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). Pokud chcete odstranit toto varování, můžete místo toho použít /reference (vlastnost Přibalit definované typy nastavená na False). V tomto případě uvedené informace poskytne primární definiční sestavení (PIA).</target> <note /> </trans-unit> <trans-unit id="ERR_GenericsUsedAcrossAssemblies"> <source>Type '{0}' from assembly '{1}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source> <target state="translated">Typ {0} ze sestavení {1} se nedá použít přes hranice sestavení, protože má argument obecného typu, který je vloženým definičním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_NoCanonicalView"> <source>Cannot find the interop type that matches the embedded interop type '{0}'. Are you missing an assembly reference?</source> <target state="translated">Nejde najít typ spolupráce, který odpovídá vloženému typu {0}. Nechybí odkaz na sestavení?</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMismatch"> <source>Module name '{0}' stored in '{1}' must match its filename.</source> <target state="translated">Název modulu {0} uložený v {1} musí odpovídat svému názvu souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleName"> <source>Invalid module name: {0}</source> <target state="translated">Neplatný název modulu: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadCompilationOptionValue"> <source>Invalid '{0}' value: '{1}'.</source> <target state="translated">Neplatná hodnota {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAppConfigPath"> <source>AppConfigPath must be absolute.</source> <target state="translated">AppConfigPath musí být absolutní.</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden"> <source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source</source> <target state="translated">Atribut {0} z modulu {1} se bude ignorovat ve prospěch instance, která se objeví ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title"> <source>Attribute will be ignored in favor of the instance appearing in source</source> <target state="translated">Atribut se bude ignorovat ve prospěch instance zobrazené ve zdroji.</target> <note /> </trans-unit> <trans-unit id="ERR_CmdOptionConflictsSource"> <source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source> <target state="translated">Atribut {0} daný ve zdrojovém souboru je v konfliktu s možností {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedBufferTooManyDimensions"> <source>A fixed buffer may only have one dimension.</source> <target state="translated">Pevná vyrovnávací paměť může mít jen jednu dimenzi.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName"> <source>Referenced assembly '{0}' does not have a strong name.</source> <target state="translated">Odkazované sestavení {0} nemá silný název.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title"> <source>Referenced assembly does not have a strong name</source> <target state="translated">Odkazované sestavení nemá silný název.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSignaturePublicKey"> <source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source> <target state="translated">V atributu AssemblySignatureKeyAttribute je uvedený neplatný veřejný klíč podpisu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypeConflictsWithDeclaration"> <source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">Typ {0} exportovaný z modulu {1} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypesConflict"> <source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">Typ {0} exportovaný z modulu {1} je v konfliktu s typem {2} exportovaným z modulu {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration"> <source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">Předaný typ {0} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypesConflict"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source> <target state="translated">Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} předaným do sestavení {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithExportedType"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} exportovaným z modulu {3}.</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch"> <source>Referenced assembly '{0}' has different culture setting of '{1}'.</source> <target state="translated">Odkazované sestavení {0} má jiné nastavení jazykové verze {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch_Title"> <source>Referenced assembly has different culture setting</source> <target state="translated">Odkazované sestavení má jiné nastavení jazykové verze.</target> <note /> </trans-unit> <trans-unit id="ERR_AgnosticToMachineModule"> <source>Agnostic assembly cannot have a processor specific module '{0}'.</source> <target state="translated">Agnostické sestavení nemůže mít modul {0} určený pro konkrétní procesor.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingMachineModule"> <source>Assembly and module '{0}' cannot target different processors.</source> <target state="translated">Sestavení a modul {0} nemůžou mířit na různé procesory.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly"> <source>Referenced assembly '{0}' targets a different processor.</source> <target state="translated">Odkazované sestavení {0} míří na jiný procesor.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly_Title"> <source>Referenced assembly targets a different processor</source> <target state="translated">Odkazované sestavení míří na jiný procesor.</target> <note /> </trans-unit> <trans-unit id="ERR_CryptoHashFailed"> <source>Cryptographic failure while creating hashes.</source> <target state="translated">Při vytváření čísel hash došlo ke kryptografické chybě.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNetModuleReference"> <source>Reference to '{0}' netmodule missing.</source> <target state="translated">Chybí odkaz na netmodule {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMustBeUnique"> <source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source> <target state="translated">Modul {0} je už v tomto sestavení definovaný. Každý modul musí mít jedinečný název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadConfigFile"> <source>Cannot read config file '{0}' -- '{1}'</source> <target state="translated">Nejde přečíst konfigurační soubor {0} -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_EncNoPIAReference"> <source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source> <target state="translated">Nedá se pokračovat, protože úprava obsahuje odkaz na vložený typ: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_EncReferenceToAddedMember"> <source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source> <target state="translated">Ke členu {0} přidanému během aktuální relace ladění se dá přistupovat jenom z jeho deklarovaného sestavení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MutuallyExclusiveOptions"> <source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source> <target state="translated">Možnosti kompilace {0} a {1} se nedají zadat současně.</target> <note /> </trans-unit> <trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage"> <source>Linked netmodule metadata must provide a full PE image: '{0}'.</source> <target state="translated">Propojená metadata netmodule musí poskytovat plnou image PE: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPrefer32OnLib"> <source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe</source> <target state="translated">Možnost /platform:anycpu32bitpreferred jde použít jenom s možnostmi /t:exe, /t:winexe a /t:appcontainerexe.</target> <note /> </trans-unit> <trans-unit id="IDS_PathList"> <source>&lt;path list&gt;</source> <target state="translated">&lt;seznam cest&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_Text"> <source>&lt;text&gt;</source> <target state="translated">&lt;text&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullPropagatingOperator"> <source>null propagating operator</source> <target state="translated">operátor šířící null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedMethod"> <source>expression-bodied method</source> <target state="translated">metoda s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedProperty"> <source>expression-bodied property</source> <target state="translated">vlastnost s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedIndexer"> <source>expression-bodied indexer</source> <target state="translated">indexer s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAutoPropertyInitializer"> <source>auto property initializer</source> <target state="translated">automatický inicializátor vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_Namespace1"> <source>&lt;namespace&gt;</source> <target state="translated">&lt;obor názvů&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefLocalsReturns"> <source>byref locals and returns</source> <target state="translated">lokální proměnné a vrácení podle odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyReferences"> <source>readonly references</source> <target state="translated">odkazy jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefStructs"> <source>ref structs</source> <target state="translated">struktury REF</target> <note /> </trans-unit> <trans-unit id="CompilationC"> <source>Compilation (C#): </source> <target state="translated">Kompilace (C#): </target> <note /> </trans-unit> <trans-unit id="SyntaxNodeIsNotWithinSynt"> <source>Syntax node is not within syntax tree</source> <target state="translated">Uzel syntaxe není ve stromu syntaxe.</target> <note /> </trans-unit> <trans-unit id="LocationMustBeProvided"> <source>Location must be provided in order to provide minimal type qualification.</source> <target state="translated">Musí být zadané umístění, aby se zajistila minimální kvalifikace typu.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeSemanticModelMust"> <source>SyntaxTreeSemanticModel must be provided in order to provide minimal type qualification.</source> <target state="translated">Musí být zadaný SyntaxTreeSemanticModel, aby se zajistila minimální kvalifikace typu.</target> <note /> </trans-unit> <trans-unit id="CantReferenceCompilationOf"> <source>Can't reference compilation of type '{0}' from {1} compilation.</source> <target state="translated">Na kompilaci typu {0} nejde odkazovat z kompilace {1}.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeAlreadyPresent"> <source>Syntax tree already present</source> <target state="translated">Strom syntaxe už je přítomný.</target> <note /> </trans-unit> <trans-unit id="SubmissionCanOnlyInclude"> <source>Submission can only include script code.</source> <target state="translated">Odeslání může zahrnovat jenom kód skriptu.</target> <note /> </trans-unit> <trans-unit id="SubmissionCanHaveAtMostOne"> <source>Submission can have at most one syntax tree.</source> <target state="translated">Odeslání musí mít aspoň jeden strom syntaxe.</target> <note /> </trans-unit> <trans-unit id="TreeMustHaveARootNodeWith"> <source>tree must have a root node with SyntaxKind.CompilationUnit</source> <target state="translated">strom musí mít kořenový uzel s prvkem SyntaxKind.CompilationUnit</target> <note /> </trans-unit> <trans-unit id="TypeArgumentCannotBeNull"> <source>Type argument cannot be null</source> <target state="translated">Argument typu nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WrongNumberOfTypeArguments"> <source>Wrong number of type arguments</source> <target state="translated">Chybný počet argumentů typu</target> <note /> </trans-unit> <trans-unit id="NameConflictForName"> <source>Name conflict for name {0}</source> <target state="translated">Konflikt u názvu {0}</target> <note /> </trans-unit> <trans-unit id="LookupOptionsHasInvalidCombo"> <source>LookupOptions has an invalid combination of options</source> <target state="translated">LookupOptions má neplatnou kombinaci možností.</target> <note /> </trans-unit> <trans-unit id="ItemsMustBeNonEmpty"> <source>items: must be non-empty</source> <target state="translated">Položky: Nesmí být prázdné.</target> <note /> </trans-unit> <trans-unit id="UseVerbatimIdentifier"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier or Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier to create identifier tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier nebo Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier můžete vytvořit tokeny identifikátorů.</target> <note /> </trans-unit> <trans-unit id="UseLiteralForTokens"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create character literal tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit znakové literálové tokeny.</target> <note /> </trans-unit> <trans-unit id="UseLiteralForNumeric"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create numeric literal tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit numerické literálové tokeny.</target> <note /> </trans-unit> <trans-unit id="ThisMethodCanOnlyBeUsedToCreateTokens"> <source>This method can only be used to create tokens - {0} is not a token kind.</source> <target state="translated">Tato metoda se dá používat jenom k vytváření tokenů – {0} není druh tokenu.</target> <note /> </trans-unit> <trans-unit id="GenericParameterDefinition"> <source>Generic parameter is definition when expected to be reference {0}</source> <target state="translated">Obecný parametr je definice, i když se očekával odkaz {0}.</target> <note /> </trans-unit> <trans-unit id="InvalidGetDeclarationNameMultipleDeclarators"> <source>Called GetDeclarationName for a declaration node that can possibly contain multiple variable declarators.</source> <target state="translated">Proběhlo volání funkce GetDeclarationName kvůli uzlu deklarací, který by mohl obsahovat několik variabilních deklarátorů.</target> <note /> </trans-unit> <trans-unit id="TreeNotPartOfCompilation"> <source>tree not part of compilation</source> <target state="translated">strom není součástí kompilace</target> <note /> </trans-unit> <trans-unit id="PositionIsNotWithinSyntax"> <source>Position is not within syntax tree with full span {0}</source> <target state="translated">Pozice není v rámci stromu syntaxe s plným rozpětím {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang"> <source>The language name '{0}' is invalid.</source> <target state="translated">Název jazyka {0} je neplatný.</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang_Title"> <source>The language name is invalid</source> <target state="translated">Název jazyka je neplatný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedTransparentIdentifierAccess"> <source>Transparent identifier member access failed for field '{0}' of '{1}'. Does the data being queried implement the query pattern?</source> <target state="translated">U pole {0} v {1} selhal přístup pro členy s transparentním identifikátorem. Implementují dotazovaná data vzor dotazu?</target> <note /> </trans-unit> <trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute"> <source>The parameter has multiple distinct default values.</source> <target state="translated">Parametr má víc odlišných výchozích hodnot.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldHasMultipleDistinctConstantValues"> <source>The field has multiple distinct constant values.</source> <target state="translated">Pole má víc odlišných konstantních hodnot.</target> <note /> </trans-unit> <trans-unit id="WRN_UnqualifiedNestedTypeInCref"> <source>Within cref attributes, nested types of generic types should be qualified.</source> <target state="translated">V atributech cref by měly být kvalifikované vnořené typy obecných typů.</target> <note /> </trans-unit> <trans-unit id="WRN_UnqualifiedNestedTypeInCref_Title"> <source>Within cref attributes, nested types of generic types should be qualified</source> <target state="translated">V atributech cref by měly být kvalifikované vnořené typy obecných typů.</target> <note /> </trans-unit> <trans-unit id="NotACSharpSymbol"> <source>Not a C# symbol.</source> <target state="translated">Nepředstavuje symbol C#.</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedUsingDirective"> <source>Unnecessary using directive.</source> <target state="translated">Nepotřebná direktiva using</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedExternAlias"> <source>Unused extern alias.</source> <target state="translated">Nepoužívaný alias extern</target> <note /> </trans-unit> <trans-unit id="ElementsCannotBeNull"> <source>Elements cannot be null.</source> <target state="translated">Elementy nemůžou mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="IDS_LIB_ENV"> <source>LIB environment variable</source> <target state="translated">proměnná prostředí LIB</target> <note /> </trans-unit> <trans-unit id="IDS_LIB_OPTION"> <source>/LIB option</source> <target state="translated">parametr /LIB</target> <note /> </trans-unit> <trans-unit id="IDS_REFERENCEPATH_OPTION"> <source>/REFERENCEPATH option</source> <target state="translated">Možnost /REFERENCEPATH</target> <note /> </trans-unit> <trans-unit id="IDS_DirectoryDoesNotExist"> <source>directory does not exist</source> <target state="translated">adresář neexistuje</target> <note /> </trans-unit> <trans-unit id="IDS_DirectoryHasInvalidPath"> <source>path is too long or invalid</source> <target state="translated">cesta je moc dlouhá nebo neplatná.</target> <note /> </trans-unit> <trans-unit id="WRN_NoRuntimeMetadataVersion"> <source>No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.</source> <target state="translated">Nenašla se žádná hodnota RuntimeMetadataVersion, žádné sestavení obsahující System.Object ani nebyla v možnostech zadaná hodnota pro RuntimeMetadataVersion.</target> <note /> </trans-unit> <trans-unit id="WRN_NoRuntimeMetadataVersion_Title"> <source>No value for RuntimeMetadataVersion found</source> <target state="translated">Nenašla se žádná hodnota pro RuntimeMetadataVersion.</target> <note /> </trans-unit> <trans-unit id="WrongSemanticModelType"> <source>Expected a {0} SemanticModel.</source> <target state="translated">Očekával se SemanticModel {0}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambda"> <source>lambda expression</source> <target state="translated">výraz lambda</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion1"> <source>Feature '{0}' is not available in C# 1. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 1. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion2"> <source>Feature '{0}' is not available in C# 2. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 2. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion3"> <source>Feature '{0}' is not available in C# 3. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 3. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion4"> <source>Feature '{0}' is not available in C# 4. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 4. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion5"> <source>Feature '{0}' is not available in C# 5. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 5. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion6"> <source>Feature '{0}' is not available in C# 6. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 6. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7"> <source>Feature '{0}' is not available in C# 7.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.0. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="IDS_VersionExperimental"> <source>'experimental'</source> <target state="translated">'"experimentální"</target> <note /> </trans-unit> <trans-unit id="PositionNotWithinTree"> <source>Position must be within span of the syntax tree.</source> <target state="translated">Pozice musí být v rozpětí stromu syntaxe.</target> <note /> </trans-unit> <trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation"> <source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source> <target state="translated">Uzel syntaxe určený ke spekulaci nemůže patřit do stromu syntaxe z aktuální kompilace.</target> <note /> </trans-unit> <trans-unit id="ChainingSpeculativeModelIsNotSupported"> <source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source> <target state="translated">Zřetězení spekulativního sémantického modelu se nepodporuje. Měli byste vytvořit spekulativní model z nespekulativního modelu ParentModel.</target> <note /> </trans-unit> <trans-unit id="IDS_ToolName"> <source>Microsoft (R) Visual C# Compiler</source> <target state="translated">Kompilátor Microsoft (R) Visual C#</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine1"> <source>{0} version {1}</source> <target state="translated">{0} verze {1}</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Všechna práva vyhrazena.</target> <note /> </trans-unit> <trans-unit id="IDS_LangVersions"> <source>Supported language versions:</source> <target state="translated">Podporované jazykové verze:</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithInitializers"> <source>'{0}': a class with the ComImport attribute cannot specify field initializers.</source> <target state="translated">{0}: Třída s atributem ComImport nemůže určovat inicializátory polí.</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong"> <source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">Místní název {0} je moc dlouhý pro PDB. Zvažte jeho zkrácení nebo kompilaci bez /debug.</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong_Title"> <source>Local name is too long for PDB</source> <target state="translated">Lokální název je moc dlouhý pro PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_RetNoObjectRequiredLambda"> <source>Anonymous function converted to a void returning delegate cannot return a value</source> <target state="translated">Anonymní funkce převedená na void, která vrací delegáta, nemůže vracet hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_TaskRetNoObjectRequiredLambda"> <source>Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task&lt;T&gt;'?</source> <target state="translated">Asynchronní lambda výraz převedený na Task a vracející delegáta nemůže vrátit hodnotu. Měli jste v úmyslu vrátit Task&lt;T&gt;?</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated"> <source>An instance of analyzer {0} cannot be created from {1} : {2}.</source> <target state="translated">Instance analyzátoru {0} nejde vytvořit z {1} : {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated_Title"> <source>An analyzer instance cannot be created</source> <target state="translated">Nedá se vytvořit instance analyzátoru.</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">Sestavení {0} neobsahuje žádné analyzátory.</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly_Title"> <source>Assembly does not contain any analyzers</source> <target state="translated">Sestavení neobsahuje žádné analyzátory.</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer"> <source>Unable to load Analyzer assembly {0} : {1}</source> <target state="translated">Nejde načíst sestavení analyzátoru {0} : {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer_Title"> <source>Unable to load Analyzer assembly</source> <target state="translated">Nejde načíst sestavení analyzátoru.</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer"> <source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source> <target state="translated">Přeskočí se některé typy v sestavení analyzátoru {0} kvůli výjimce ReflectionTypeLoadException: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadRulesetFile"> <source>Error reading ruleset file {0} - {1}</source> <target state="translated">Chyba při čtení souboru sady pravidel {0} - {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadPdbData"> <source>Error reading debug information for '{0}'</source> <target state="translated">Chyba při čtení informací ladění pro {0}</target> <note /> </trans-unit> <trans-unit id="IDS_OperationCausedStackOverflow"> <source>Operation caused a stack overflow.</source> <target state="translated">Operace způsobila přetečení zásobníku.</target> <note /> </trans-unit> <trans-unit id="WRN_IdentifierOrNumericLiteralExpected"> <source>Expected identifier or numeric literal.</source> <target state="translated">Očekával se identifikátor nebo číselný literál.</target> <note /> </trans-unit> <trans-unit id="WRN_IdentifierOrNumericLiteralExpected_Title"> <source>Expected identifier or numeric literal</source> <target state="translated">Očekával se identifikátor nebo číselný literál.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerOnNonAutoProperty"> <source>Only auto-implemented properties can have initializers.</source> <target state="translated">Jenom automaticky implementované vlastnosti můžou mít inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyMustHaveGetAccessor"> <source>Auto-implemented properties must have get accessors.</source> <target state="translated">Automaticky implementované vlastnosti musí mít přistupující objekty get.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyMustOverrideSet"> <source>Auto-implemented properties must override all accessors of the overridden property.</source> <target state="translated">Automaticky implementované vlastnosti musí přepsat všechny přistupující objekty přepsané vlastnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerInStructWithoutExplicitConstructor"> <source>Structs without explicit constructors cannot contain members with initializers.</source> <target state="translated">Struktury bez explicitních konstruktorů nemůžou obsahovat členy s inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_EncodinglessSyntaxTree"> <source>Cannot emit debug information for a source text without encoding.</source> <target state="translated">Nejde vygenerovat ladicí informace pro zdrojový text bez kódování.</target> <note /> </trans-unit> <trans-unit id="ERR_BlockBodyAndExpressionBody"> <source>Block bodies and expression bodies cannot both be provided.</source> <target state="translated">Nejde zadat těla bloků i těla výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchFallOut"> <source>Control cannot fall out of switch from final case label ('{0}')</source> <target state="translated">Řízení nemůže opustit příkaz switch z posledního příkazu case ('{0}')</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedBoundGenericName"> <source>Type arguments are not allowed in the nameof operator.</source> <target state="translated">Argumenty typů nejsou v operátoru nameof povoleny.</target> <note /> </trans-unit> <trans-unit id="ERR_NullPropagatingOpInExpressionTree"> <source>An expression tree lambda may not contain a null propagating operator.</source> <target state="translated">Strom výrazu lambda nesmí obsahovat operátor šířící null.</target> <note /> </trans-unit> <trans-unit id="ERR_DictionaryInitializerInExpressionTree"> <source>An expression tree lambda may not contain a dictionary initializer.</source> <target state="translated">Strom výrazu lambda nesmí obsahovat inicializátor slovníku.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionCollectionElementInitializerInExpressionTree"> <source>An extension Add method is not supported for a collection initializer in an expression lambda.</source> <target state="translated">Rozšiřující metoda Add není pro inicializátor kolekce v lambda výrazu podporovaná.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNameof"> <source>nameof operator</source> <target state="translated">operátor nameof</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDictionaryInitializer"> <source>dictionary initializer</source> <target state="translated">inicializátor slovníku</target> <note /> </trans-unit> <trans-unit id="ERR_UnclosedExpressionHole"> <source>Missing close delimiter '}' for interpolated expression started with '{'.</source> <target state="translated">Chybí uzavírací oddělovač } pro interpolovaný výraz začínající na {.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleLineCommentInExpressionHole"> <source>A single-line comment may not be used in an interpolated string.</source> <target state="translated">V interpolovaném řetězci se nemůže používat jednořádkový komentář.</target> <note /> </trans-unit> <trans-unit id="ERR_InsufficientStack"> <source>An expression is too long or complex to compile</source> <target state="translated">Výraz je pro zkompilování moc dlouhý nebo složitý.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionHasNoName"> <source>Expression does not have a name.</source> <target state="translated">Výraz není pojmenovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_SubexpressionNotInNameof"> <source>Sub-expression cannot be used in an argument to nameof.</source> <target state="translated">Dílčí výraz se jako argument nameof nedá použít.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasQualifiedNameNotAnExpression"> <source>An alias-qualified name is not an expression.</source> <target state="translated">Název kvalifikovaný pomocí aliasu není výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_NameofMethodGroupWithTypeParameters"> <source>Type parameters are not allowed on a method group as an argument to 'nameof'.</source> <target state="translated">Parametry typu se u skupiny metod nedají použít jako argument nameof.</target> <note /> </trans-unit> <trans-unit id="NoNoneSearchCriteria"> <source>SearchCriteria is expected.</source> <target state="translated">Očekává se třída SearchCriteria.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCulture"> <source>Assembly culture strings may not contain embedded NUL characters.</source> <target state="translated">Řetězce jazykové verze sestavení nesmí obsahovat vložené znaky NUL.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUsingStatic"> <source>using static</source> <target state="translated">using static</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInterpolatedStrings"> <source>interpolated strings</source> <target state="translated">interpolované řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_AwaitInCatchAndFinally"> <source>await in catch blocks and finally blocks</source> <target state="translated">očekávat v blocích catch a blocích finally</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureBinaryLiteral"> <source>binary literals</source> <target state="translated">binární literály</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDigitSeparator"> <source>digit separators</source> <target state="translated">oddělovače číslic</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLocalFunctions"> <source>local functions</source> <target state="translated">místní funkce</target> <note /> </trans-unit> <trans-unit id="ERR_UnescapedCurly"> <source>A '{0}' character must be escaped (by doubling) in an interpolated string.</source> <target state="translated">Znak {0} musí být v interpolovaném řetězci uvozený (zdvojeným znakem).</target> <note /> </trans-unit> <trans-unit id="ERR_EscapedCurly"> <source>A '{0}' character may only be escaped by doubling '{0}{0}' in an interpolated string.</source> <target state="translated">V interpolovaném řetězci může být znak {0} uvozený jenom zdvojeným znakem ({0}{0}).</target> <note /> </trans-unit> <trans-unit id="ERR_TrailingWhitespaceInFormatSpecifier"> <source>A format specifier may not contain trailing whitespace.</source> <target state="translated">Specifikátor formátu nesmí na konci obsahovat mezeru.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyFormatSpecifier"> <source>Empty format specifier.</source> <target state="translated">Prázdný specifikátor formátu</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorInReferencedAssembly"> <source>There is an error in a referenced assembly '{0}'.</source> <target state="translated">V odkazovaném sestavení {0} je chyba.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionOrDeclarationExpected"> <source>Expression or declaration statement expected.</source> <target state="translated">Očekával se příkaz s výrazem nebo deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_NameofExtensionMethod"> <source>Extension method groups are not allowed as an argument to 'nameof'.</source> <target state="translated">Skupiny metod rozšíření nejsou povolené jako argument pro nameof.</target> <note /> </trans-unit> <trans-unit id="WRN_AlignmentMagnitude"> <source>Alignment value {0} has a magnitude greater than {1} and may result in a large formatted string.</source> <target state="translated">Hodnota zarovnání {0} má velikost větší než {1} a jejím výsledkem může být velký formátovaný řetězec.</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedExternAlias_Title"> <source>Unused extern alias</source> <target state="translated">Nepoužívaný externí alias</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedUsingDirective_Title"> <source>Unnecessary using directive</source> <target state="translated">Nepotřebná direktiva using</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title"> <source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source> <target state="translated">Přeskočí načtení typů v sestavení analyzátoru, které selžou kvůli výjimce ReflectionTypeLoadException.</target> <note /> </trans-unit> <trans-unit id="WRN_AlignmentMagnitude_Title"> <source>Alignment value has a magnitude that may result in a large formatted string</source> <target state="translated">Hodnota zarovnání má velikost, jejímž výsledkem může být velký formátovaný řetězec.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantStringTooLong"> <source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source> <target state="translated">Délka konstanty String, která je výsledkem zřetězení, překračuje hodnotu System.Int32.MaxValue. Zkuste rozdělit řetězec na více konstant.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleTooFewElements"> <source>Tuple must contain at least two elements.</source> <target state="translated">Řazená kolekce členů musí obsahovat minimálně dva elementy.</target> <note /> </trans-unit> <trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition"> <source>Debug entry point must be a definition of a method declared in the current compilation.</source> <target state="translated">Vstupní bod ladění musí být definicí metody deklarované v aktuální kompilaci.</target> <note /> </trans-unit> <trans-unit id="ERR_LoadDirectiveOnlyAllowedInScripts"> <source>#load is only allowed in scripts</source> <target state="translated">#load se povoluje jenom ve skriptech</target> <note /> </trans-unit> <trans-unit id="ERR_PPLoadFollowsToken"> <source>Cannot use #load after first token in file</source> <target state="translated">Za prvním tokenem v souboru se nedá použít #load.</target> <note /> </trans-unit> <trans-unit id="CouldNotFindFile"> <source>Could not find file.</source> <target state="translated">Nepovedlo se najít soubor.</target> <note>File path referenced in source (#load) could not be resolved.</note> </trans-unit> <trans-unit id="SyntaxTreeFromLoadNoRemoveReplace"> <source>SyntaxTree resulted from a #load directive and cannot be removed or replaced directly.</source> <target state="translated">SyntaxTree je výsledkem direktivy #load a nedá se odebrat nebo nahradit přímo.</target> <note /> </trans-unit> <trans-unit id="ERR_SourceFileReferencesNotSupported"> <source>Source file references are not supported.</source> <target state="translated">Odkazy na zdrojový soubor se nepodporují.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPathMap"> <source>The pathmap option was incorrectly formatted.</source> <target state="translated">Možnost pathmap nebyla správně naformátovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidReal"> <source>Invalid real literal.</source> <target state="translated">Neplatný literál real</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCannotBeRefReturning"> <source>Auto-implemented properties cannot return by reference</source> <target state="translated">Automaticky implementované vlastnosti nejde vrátit pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefPropertyMustHaveGetAccessor"> <source>Properties which return by reference must have a get accessor</source> <target state="translated">Vlastnosti, které vracejí pomocí odkazu, musí mít přístupový objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_RefPropertyCannotHaveSetAccessor"> <source>Properties which return by reference cannot have set accessors</source> <target state="translated">Vlastnosti, které vracejí pomocí odkazu, nemůžou mít přístupové objekty set.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeRefReturnOnOverride"> <source>'{0}' must match by reference return of overridden member '{1}'</source> <target state="translated">{0} musí odpovídat návratu pomocí odkazu přepsaného člena {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MustNotHaveRefReturn"> <source>By-reference returns may only be used in methods that return by reference</source> <target state="translated">Vrácení podle odkazu se dají používat jenom v metodách, které vracejí pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_MustHaveRefReturn"> <source>By-value returns may only be used in methods that return by value</source> <target state="translated">Vrácení podle hodnoty se dají používat jenom v metodách, které vracejí podle hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnMustHaveIdentityConversion"> <source>The return expression must be of type '{0}' because this method returns by reference</source> <target state="translated">Návratový výraz musí být typu {0}, protože tato metoda vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongRefReturn"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have matching return by reference.</source> <target state="translated">{0} neimplementuje člena rozhraní {1}. {2} nemůže implementovat {1}, protože nemá odpovídající návrat pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturnRef"> <source>The body of '{0}' cannot be an iterator block because '{0}' returns by reference</source> <target state="translated">Hlavní část objektu {0} nemůže představovat blok iterátoru, protože {0} se vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRefReturnExpressionTree"> <source>Lambda expressions that return by reference cannot be converted to expression trees</source> <target state="translated">Výrazy lambda, které se vrací pomocí odkazu, nejde převést na stromy výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallInExpressionTree"> <source>An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference</source> <target state="translated">Lambda stromu výrazů nesmí obsahovat volání do metody, vlastnosti nebo indexeru, které vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLvalueExpected"> <source>An expression cannot be used in this context because it may not be passed or returned by reference</source> <target state="translated">Výraz nelze v tomto kontextu použít, protože nesmí být předaný nebo vrácený pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnNonreturnableLocal"> <source>Cannot return '{0}' by reference because it was initialized to a value that cannot be returned by reference</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnNonreturnableLocal2"> <source>Cannot return by reference a member of '{0}' because it was initialized to a value that cannot be returned by reference</source> <target state="translated">Člen pro {0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocal"> <source>Cannot return '{0}' by reference because it is read-only</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože je to hodnota jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnRangeVariable"> <source>Cannot return the range variable '{0}' by reference</source> <target state="translated">Proměnnou rozsahu {0} nejde vrátit pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocalCause"> <source>Cannot return '{0}' by reference because it is a '{1}'</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože je to {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocal2Cause"> <source>Cannot return fields of '{0}' by reference because it is a '{1}'</source> <target state="translated">Pole elementu {0} nejde vrátit pomocí odkazu, protože je to {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonly"> <source>A readonly field cannot be returned by writable reference</source> <target state="translated">Pole jen pro čtení nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyStatic"> <source>A static readonly field cannot be returned by writable reference</source> <target state="translated">Statické pole jen pro čtení nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonly2"> <source>Members of readonly field '{0}' cannot be returned by writable reference</source> <target state="translated">Členy pole jen pro čtení {0} nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be returned by writable reference</source> <target state="translated">Pole statického pole jen pro čtení {0} nejdou vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnParameter"> <source>Cannot return a parameter by reference '{0}' because it is not a ref or out parameter</source> <target state="translated">Parametr nejde vrátit pomocí odkazu {0}, protože nejde o parametr Ref nebo Out.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnParameter2"> <source>Cannot return by reference a member of parameter '{0}' because it is not a ref or out parameter</source> <target state="translated">Člen parametru {0} nejde vrátit pomocí odkazu, protože nejde o parametr ref nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLocal"> <source>Cannot return local '{0}' by reference because it is not a ref local</source> <target state="translated">Lokální proměnnou {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLocal2"> <source>Cannot return a member of local '{0}' by reference because it is not a ref local</source> <target state="translated">Člen lokální proměnné {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnStructThis"> <source>Struct members cannot return 'this' or other instance members by reference</source> <target state="translated">Členy struktury nemůžou vracet this nebo jiné členy instance pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeOther"> <source>Expression cannot be used in this context because it may indirectly expose variables outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde výraz použít, protože může nepřímo vystavit proměnné mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeLocal"> <source>Cannot use local '{0}' in this context because it may expose referenced variables outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít místní {0}, protože může vystavit odkazované proměnné mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeCall"> <source>Cannot use a result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít výsledek z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeCall2"> <source>Cannot use a member of result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít člena výsledku z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_CallArgMixing"> <source>This combination of arguments to '{0}' is disallowed because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">Tato kombinace argumentů pro {0} je zakázaná, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_MismatchedRefEscapeInTernary"> <source>Branches of a ref conditional operator cannot refer to variables with incompatible declaration scopes</source> <target state="translated">Větve podmíněného operátoru REF nemůžou odkazovat na proměnné s nekompatibilními obory deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeStackAlloc"> <source>A result of a stackalloc expression of type '{0}' cannot be used in this context because it may be exposed outside of the containing method</source> <target state="translated">Výsledek výrazu stackalloc typu {0} nejde v tomto kontextu použít, protože může být vystavený mimo obsahující metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializeByValueVariableWithReference"> <source>Cannot initialize a by-value variable with a reference</source> <target state="translated">Proměnnou podle hodnoty nejde inicializovat odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializeByReferenceVariableWithValue"> <source>Cannot initialize a by-reference variable with a value</source> <target state="translated">Proměnnou podle odkazu nejde inicializovat hodnotou.</target> <note /> </trans-unit> <trans-unit id="ERR_RefAssignmentMustHaveIdentityConversion"> <source>The expression must be of type '{0}' because it is being assigned by reference</source> <target state="translated">Výraz musí být typu {0}, protože se přiřazuje pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ByReferenceVariableMustBeInitialized"> <source>A declaration of a by-reference variable must have an initializer</source> <target state="translated">Deklarace proměnné podle odkazu musí mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonDelegateCantUseLocal"> <source>Cannot use ref local '{0}' inside an anonymous method, lambda expression, or query expression</source> <target state="translated">Místní hodnotu odkazu {0} nejde použít uvnitř anonymní metody, výrazu lambda nebo výrazu dotazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorLocalType"> <source>Iterators cannot have by-reference locals</source> <target state="translated">Iterátory nemůžou mít lokální proměnné podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncLocalType"> <source>Async methods cannot have by-reference locals</source> <target state="translated">Asynchronní metody nemůžou mít lokální proměnné podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallAndAwait"> <source>'await' cannot be used in an expression containing a call to '{0}' because it returns by reference</source> <target state="translated">'Argument await nejde použít ve výrazu obsahujícím volání do {0}, protože se vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalAndAwait"> <source>'await' cannot be used in an expression containing a ref conditional operator</source> <target state="translated">'Await nejde použít ve výrazu, který obsahuje podmíněný operátor REF.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalNeedsTwoRefs"> <source>Both conditional operator values must be ref values or neither may be a ref value</source> <target state="translated">Obě hodnoty podmíněného operátoru musí být hodnoty ref nebo ani jedna z nich nesmí být hodnota ref.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalDifferentTypes"> <source>The expression must be of type '{0}' to match the alternative ref value</source> <target state="translated">Výraz musí být typu {0}, aby odpovídal alternativní hodnotě ref.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsLocalFunction"> <source>An expression tree may not contain a reference to a local function</source> <target state="translated">Strom výrazů nesmí obsahovat odkaz na místní funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicLocalFunctionParamsParameter"> <source>Cannot pass argument with dynamic type to params parameter '{0}' of local function '{1}'.</source> <target state="translated">Nejde předat argument dynamického typu s parametrem params {0} místní funkce {1}.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeIsNotASubmission"> <source>Syntax tree should be created from a submission.</source> <target state="translated">Strom syntaxe by se měl vytvořit z odeslání.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyUserStrings"> <source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals.</source> <target state="translated">Kombinovaná délka uživatelských řetězců, které používá tento program, překročila povolený limit. Zkuste omezit použití řetězcových literálů.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternNullableType"> <source>It is not legal to use nullable type '{0}?' in a pattern; use the underlying type '{0}' instead.</source> <target state="translated">Ve vzoru se nepovoluje použití typu s možnou hodnotou null {0}?. Místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PeWritingFailure"> <source>An error occurred while writing the output file: {0}.</source> <target state="translated">Při zápisu výstupního souboru došlo k chybě: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleDuplicateElementName"> <source>Tuple element names must be unique.</source> <target state="translated">Názvy elementů řazené kolekce členů musí být jedinečné.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementName"> <source>Tuple element name '{0}' is only allowed at position {1}.</source> <target state="translated">Název elementu řazené kolekce členů {0} je povolený jenom v pozici {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementNameAnyPosition"> <source>Tuple element name '{0}' is disallowed at any position.</source> <target state="translated">Název elementu řazené kolekce členů {0} je zakázaný v jakékoliv pozici.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedTypeMemberNotFoundInAssembly"> <source>Member '{0}' was not found on type '{1}' from assembly '{2}'.</source> <target state="translated">Nenašel se člen {0} v typu {1} ze sestavení {2}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTuples"> <source>tuples</source> <target state="translated">řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="ERR_MissingDeconstruct"> <source>No suitable 'Deconstruct' instance or extension method was found for type '{0}', with {1} out parameters and a void return type.</source> <target state="translated">Pro typ {0} s výstupními parametry ({1}) a návratovým typem void se nenašla žádná vhodná instance Deconstruct nebo rozšiřující metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructRequiresExpression"> <source>Deconstruct assignment requires an expression with a type on the right-hand-side.</source> <target state="translated">Dekonstrukční přiřazení vyžaduje výraz s typem na pravé straně.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchExpressionValueExpected"> <source>The switch expression must be a value; found '{0}'.</source> <target state="translated">Výraz switch musí být hodnota. Bylo nalezeno: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternWrongType"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}'.</source> <target state="translated">Výraz typu {0} nelze zpracovat vzorem typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning"> <source>Attribute '{0}' is ignored when public signing is specified.</source> <target state="translated">Atribut {0} se ignoruje, když je zadané veřejné podepisování.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title"> <source>Attribute is ignored when public signing is specified.</source> <target state="translated">Atribut se ignoruje, když je zadané veřejné podepisování.</target> <note /> </trans-unit> <trans-unit id="ERR_OptionMustBeAbsolutePath"> <source>Option '{0}' must be an absolute path.</source> <target state="translated">Možnost {0} musí být absolutní cesta.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionNotTupleCompatible"> <source>Tuple with {0} elements cannot be converted to type '{1}'.</source> <target state="translated">Řazená kolekce členů s {0} elementy se nedá převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOutVar"> <source>out variable declaration</source> <target state="translated">deklarace externí proměnné</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList"> <source>Reference to an implicitly-typed out variable '{0}' is not permitted in the same argument list.</source> <target state="translated">Odkaz na implicitně typovanou externí proměnnou {0} není povolený ve stejném seznamu argumentů.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailedForImplicitlyTypedOutVariable"> <source>Cannot infer the type of implicitly-typed out variable '{0}'.</source> <target state="translated">Nejde odvodit typ implicitně typované externí proměnné {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable"> <source>Cannot infer the type of implicitly-typed deconstruction variable '{0}'.</source> <target state="translated">Nejde odvodit typ dekonstrukční proměnné {0} s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_DiscardTypeInferenceFailed"> <source>Cannot infer the type of implicitly-typed discard.</source> <target state="translated">Nejde odvodit typ zahození s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructWrongCardinality"> <source>Cannot deconstruct a tuple of '{0}' elements into '{1}' variables.</source> <target state="translated">Řazenou kolekci členů s {0} prvky nejde dekonstruovat na proměnné {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotDeconstructDynamic"> <source>Cannot deconstruct dynamic objects.</source> <target state="translated">Dynamické objekty nejde dekonstruovat.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructTooFewElements"> <source>Deconstruction must contain at least two variables.</source> <target state="translated">Dekonstrukce musí obsahovat aspoň dvě proměnné.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source> <target state="translated">Název elementu řazené kolekce členů {0} se ignoruje, protože cílovým typem {1} je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source> <target state="translated">Název elementu řazené kolekce členů se ignoruje, protože cílem přiřazení je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct"> <source>Predefined type '{0}' must be a struct.</source> <target state="translated">Předdefinovaný typ {0} musí být struktura.</target> <note /> </trans-unit> <trans-unit id="ERR_NewWithTupleTypeSyntax"> <source>'new' cannot be used with tuple type. Use a tuple literal expression instead.</source> <target state="translated">'new není možné použít s typem řazené kolekce členů. Použijte raději literálový výraz řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructionVarFormDisallowsSpecificType"> <source>Deconstruction 'var (...)' form disallows a specific type for 'var'.</source> <target state="translated">Forma dekonstrukce var (...) neumožňuje použít pro var konkrétní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesAttributeMissing"> <source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">Nejde definovat třídu nebo člen, který používá řazenou kolekci členů, protože se nenašel kompilátor požadovaný typem {0}. Chybí vám odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitTupleElementNamesAttribute"> <source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source> <target state="translated">System.Runtime.CompilerServices.TupleElementNamesAttribute nejde odkazovat explicitně. K definici názvů řazené kolekce členů použijte její syntaxi.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsOutVariable"> <source>An expression tree may not contain an out argument variable declaration.</source> <target state="translated">Strom výrazů nesmí obsahovat deklaraci proměnné argumentu out.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsDiscard"> <source>An expression tree may not contain a discard.</source> <target state="translated">Strom výrazů nesmí obsahovat zahození.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsIsMatch"> <source>An expression tree may not contain an 'is' pattern-matching operator.</source> <target state="translated">Strom výrazů nesmí obsahovat operátor odpovídající vzoru is.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleLiteral"> <source>An expression tree may not contain a tuple literal.</source> <target state="translated">Strom výrazů nesmí obsahovat literál řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleConversion"> <source>An expression tree may not contain a tuple conversion.</source> <target state="translated">Strom výrazů nesmí obsahovat převod řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_SourceLinkRequiresPdb"> <source>/sourcelink switch is only supported when emitting PDB.</source> <target state="translated">Přepínač /sourcelink je podporovaný jen při vydávání PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedWithoutPdb"> <source>/embed switch is only supported when emitting a PDB.</source> <target state="translated">Přepínač /embed je podporovaný jen při vydávání souboru PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInstrumentationKind"> <source>Invalid instrumentation kind: {0}</source> <target state="translated">Neplatný typ instrumentace: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_VarInvocationLvalueReserved"> <source>The syntax 'var (...)' as an lvalue is reserved.</source> <target state="translated">Syntaxe 'var (...)' jako l-hodnota je vyhrazená.</target> <note /> </trans-unit> <trans-unit id="ERR_SemiOrLBraceOrArrowExpected"> <source>{ or ; or =&gt; expected</source> <target state="translated">Očekávaly se znaky { nebo ; nebo =&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_ThrowMisplaced"> <source>A throw expression is not allowed in this context.</source> <target state="translated">Výraz throw není v tomto kontextu povolený.</target> <note /> </trans-unit> <trans-unit id="ERR_DeclarationExpressionNotPermitted"> <source>A declaration is not allowed in this context.</source> <target state="translated">Deklarace není v tomto kontextu povolená.</target> <note /> </trans-unit> <trans-unit id="ERR_MustDeclareForeachIteration"> <source>A foreach loop must declare its iteration variables.</source> <target state="translated">Smyčka foreach musí deklarovat své proměnné iterace.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesInDeconstruction"> <source>Tuple element names are not permitted on the left of a deconstruction.</source> <target state="translated">Na levé straně dekonstrukce nejsou povolené názvy prvků řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleBadNegCast"> <source>To cast a negative value, you must enclose the value in parentheses.</source> <target state="translated">Pokud se má přetypovat záporná hodnota, musí být uzavřená v závorkách.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsThrowExpression"> <source>An expression tree may not contain a throw-expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz throw.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAssemblyName"> <source>Invalid assembly name: {0}</source> <target state="translated">Neplatný název sestavení: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncMethodBuilderTaskProperty"> <source>For type '{0}' to be used as an AsyncMethodBuilder for type '{1}', its Task property should return type '{1}' instead of type '{2}'.</source> <target state="translated">Aby se typ {0} mohl použít jako AsyncMethodBuilder pro typ {1}, měla by jeho vlastnost Task vracet typ {1} místo typu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeForwardedToMultipleAssemblies"> <source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source> <target state="translated">Modul {0} v sestavení {1} předává typ {2} několika sestavením: {3} a {4}.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternDynamicType"> <source>It is not legal to use the type 'dynamic' in a pattern.</source> <target state="translated">Není povoleno použít typ dynamic ve vzorku.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDocumentationMode"> <source>Provided documentation mode is unsupported or invalid: '{0}'.</source> <target state="translated">Zadaný režim dokumentace je nepodporovaný nebo neplatný: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSourceCodeKind"> <source>Provided source code kind is unsupported or invalid: '{0}'</source> <target state="translated">Zadaný druh zdrojového kódu je nepodporovaný nebo neplatný: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadLanguageVersion"> <source>Provided language version is unsupported or invalid: '{0}'.</source> <target state="translated">Zadaná verze jazyka je nepodporovaná nebo neplatná: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocessingSymbol"> <source>Invalid name for a preprocessing symbol; '{0}' is not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; {0} není platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_1"> <source>Feature '{0}' is not available in C# 7.1. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.1. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_2"> <source>Feature '{0}' is not available in C# 7.2. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.2. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersionCannotHaveLeadingZeroes"> <source>Specified language version '{0}' cannot have leading zeroes</source> <target state="translated">Zadaná verze jazyka {0} nemůže obsahovat úvodní nuly.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidAssignment"> <source>A value of type 'void' may not be assigned.</source> <target state="translated">Hodnota typu void se nesmí přiřazovat.</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental"> <source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">{0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání.</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental_Title"> <source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">Typ slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změnám nebo odebrání.</target> <note /> </trans-unit> <trans-unit id="ERR_CompilerAndLanguageVersion"> <source>Compiler version: '{0}'. Language version: {1}.</source> <target state="translated">Verze kompilátoru: {0}. Jazyková verze: {1}</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncMain"> <source>async main</source> <target state="translated">Asynchronní funkce main</target> <note /> </trans-unit> <trans-unit id="ERR_TupleInferredNamesNotAvailable"> <source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source> <target state="translated">Název elementu řazené kolekce členů {0} je odvozený. Pokud k elementu chcete získat přístup pomocí jeho odvozeného názvu, použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidInTuple"> <source>A tuple may not contain a value of type 'void'.</source> <target state="translated">Řazená kolekce členů nemůže obsahovat hodnotu typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_NonTaskMainCantBeAsync"> <source>A void or int returning entry point cannot be async</source> <target state="translated">Vstupní bod, který vrací void nebo int, nemůže být asynchronní.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternWrongGenericTypeInVersion"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater.</source> <target state="translated">V C# {2} nelze výraz typu {0} zpracovat vzorem typu {1}. Použijte prosím jazyk verze {3} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLocalFunction"> <source>The local function '{0}' is declared but never used</source> <target state="translated">Lokální funkce {0} je deklarovaná, ale vůbec se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLocalFunction_Title"> <source>Local function is declared but never used</source> <target state="translated">Lokální funkce je deklarovaná, ale vůbec se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalFunctionMissingBody"> <source>Local function '{0}' must declare a body because it is not marked 'static extern'.</source> <target state="translated">Místní funkce {0} musí deklarovat tělo, protože není označená jako static extern.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInfo"> <source>Unable to read debug information of method '{0}' (token 0x{1:X8}) from assembly '{2}'</source> <target state="translated">Informace o ladění metody {0} (token 0x{1:X8}) ze sestavení {2} nelze přečíst.</target> <note /> </trans-unit> <trans-unit id="IConversionExpressionIsNotCSharpConversion"> <source>{0} is not a valid C# conversion expression</source> <target state="translated">Výraz {0} není platným výrazem převodu C#.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicLocalFunctionTypeParameter"> <source>Cannot pass argument with dynamic type to generic local function '{0}' with inferred type arguments.</source> <target state="translated">Obecné lokální funkci {0} s odvozenými argumenty typu nelze předat argument s dynamickým typem.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLeadingDigitSeparator"> <source>leading digit separator</source> <target state="translated">oddělovač úvodní číslice</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitReservedAttr"> <source>Do not use '{0}'. This is reserved for compiler usage.</source> <target state="translated">Nepoužívejte {0}. Je vyhrazený pro použití v kompilátoru.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeReserved"> <source>The type name '{0}' is reserved to be used by the compiler.</source> <target state="translated">Název typu {0} je vyhrazený pro použití kompilátorem.</target> <note /> </trans-unit> <trans-unit id="ERR_InExtensionMustBeValueType"> <source>The first parameter of the 'in' extension method '{0}' must be a concrete (non-generic) value type.</source> <target state="translated">Prvním parametrem metody rozšíření in {0} musí být konkrétní (neobecný) typ hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldsInRoStruct"> <source>Instance fields of readonly structs must be readonly.</source> <target state="translated">Pole instancí struktur jen pro čtení musí být jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropsInRoStruct"> <source>Auto-implemented instance properties in readonly structs must be readonly.</source> <target state="translated">Vlastnosti automaticky implementované instance ve strukturách jen pro čtení musí být jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldlikeEventsInRoStruct"> <source>Field-like events are not allowed in readonly structs.</source> <target state="translated">Události podobné poli nejsou povolené ve strukturách jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefExtensionMethods"> <source>ref extension methods</source> <target state="translated">rozšiřující metody REF</target> <note /> </trans-unit> <trans-unit id="ERR_StackAllocConversionNotPossible"> <source>Conversion of a stackalloc expression of type '{0}' to type '{1}' is not possible.</source> <target state="translated">Převod výrazu stackalloc typu {0} na typ {1} není možný.</target> <note /> </trans-unit> <trans-unit id="ERR_RefExtensionMustBeValueTypeOrConstrainedToOne"> <source>The first parameter of a 'ref' extension method '{0}' must be a value type or a generic type constrained to struct.</source> <target state="translated">První parametr rozšiřující metody ref {0} musí být typem hodnoty nebo obecným typem omezeným na strukturu.</target> <note /> </trans-unit> <trans-unit id="ERR_OutAttrOnInParam"> <source>An in parameter cannot have the Out attribute.</source> <target state="translated">Parametr in nemůže obsahovat atribut Out.</target> <note /> </trans-unit> <trans-unit id="ICompoundAssignmentOperationIsNotCSharpCompoundAssignment"> <source>{0} is not a valid C# compound assignment operation</source> <target state="translated">{0} není platná operace složeného přiřazení jazyka C#.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalse"> <source>Filter expression is a constant 'false', consider removing the catch clause</source> <target state="translated">Výraz filtru je konstantní hodnota false. Zvažte odebrání klauzule catch.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalse_Title"> <source>Filter expression is a constant 'false'</source> <target state="translated">Výraz filtru je konstantní hodnota false.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalseRedundantTryCatch"> <source>Filter expression is a constant 'false', consider removing the try-catch block</source> <target state="translated">Výraz filtru je konstantní hodnota false. Zvažte odebrání bloku try-catch.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalseRedundantTryCatch_Title"> <source>Filter expression is a constant 'false'. </source> <target state="translated">Výraz filtru je konstantní hodnota false. </target> <note /> </trans-unit> <trans-unit id="ERR_CantUseVoidInArglist"> <source>__arglist cannot have an argument of void type</source> <target state="translated">__arglist nemůže mít argument typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalInInterpolation"> <source>A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression.</source> <target state="translated">Podmíněný výraz se nedá použít přímo v interpolaci řetězce, protože na konci interpolace je dvojtečka. Dejte podmíněný výraz do závorek.</target> <note /> </trans-unit> <trans-unit id="ERR_DoNotUseFixedBufferAttrOnProperty"> <source>Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property</source> <target state="translated">Nepoužívejte u vlastnosti atribut System.Runtime.CompilerServices.FixedBuffer.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_3"> <source>Feature '{0}' is not available in C# 7.3. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.3. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributesOnBackingFieldsNotAvailable"> <source>Field-targeted attributes on auto-properties are not supported in language version {0}. Please use language version {1} or greater.</source> <target state="translated">Atributy cílící na pole se u automatických vlastností v jazyku verze {0} nepodporují. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributesOnBackingFieldsNotAvailable_Title"> <source>Field-targeted attributes on auto-properties are not supported in this version of the language.</source> <target state="translated">Atributy cílící na pole se u automatických vlastností v této verzi jazyka nepodporují.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncStreams"> <source>async streams</source> <target state="translated">asynchronní streamy</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIAsyncDisp"> <source>'{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.</source> <target state="translated">{0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync.</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetAsyncEnumerator"> <source>Asynchronous foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNextAsync' method and public 'Current' property</source> <target state="translated">Asynchronní příkaz foreach vyžaduje, aby návratový typ {0} pro {1} měl vhodnou veřejnou metodu MoveNextAsync a veřejnou vlastnost Current.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleIAsyncEnumOfT"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainConversionOrEqualityOperators"> <source>Conversion, equality, or inequality operators declared in interfaces must be abstract</source> <target state="needs-review-translation">Rozhraní nemůžou obsahovat operátory převodu, rovnosti nebo nerovnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation"> <source>Target runtime doesn't support default interface implementation.</source> <target state="translated">Cílový modul runtime nepodporuje implementaci výchozího rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support default interface implementation.</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože cílový modul runtime nepodporuje implementaci výchozího rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitImplementationOfNonPublicInterfaceMember"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement a non-public member in C# {3}. Please use language version '{4}' or greater.</source> <target state="new">'{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement a non-public member in C# {3}. Please use language version '{4}' or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_MostSpecificImplementationIsNotFound"> <source>Interface member '{0}' does not have a most specific implementation. Neither '{1}', nor '{2}' are most specific.</source> <target state="translated">Člen rozhraní {0} nemá nejvíce specifickou implementaci. {1} ani {2} nejsou nejvíce specifické.</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because feature '{3}' is not available in C# {4}. Please use language version '{5}' or greater.</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože funkce {3} není v jazyce C# {4} k dispozici. Použijte prosím verzi jazyka {5} nebo vyšší.</target> <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="cs" original="../CSharpResources.resx"> <body> <trans-unit id="CallingConventionTypeIsInvalid"> <source>Cannot use '{0}' as a calling convention modifier.</source> <target state="translated">{0} se nedá použít jako modifikátor konvence volání.</target> <note /> </trans-unit> <trans-unit id="CallingConventionTypesRequireUnmanaged"> <source>Passing '{0}' is not valid unless '{1}' is 'SignatureCallingConvention.Unmanaged'.</source> <target state="translated">Pokud {1} není SignatureCallingConvention.Unmanaged, předání hodnoty {0} není platné.</target> <note /> </trans-unit> <trans-unit id="CannotCreateConstructedFromConstructed"> <source>Cannot create constructed generic type from another constructed generic type.</source> <target state="translated">Konstruovaný obecný typ nejde vytvořit z jiného konstruovaného obecného typu.</target> <note /> </trans-unit> <trans-unit id="CannotCreateConstructedFromNongeneric"> <source>Cannot create constructed generic type from non-generic type.</source> <target state="translated">Konstruovaný obecný typ nejde vytvořit z jiného než obecného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractConversionNotInvolvingContainedType"> <source>User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type</source> <target state="new">User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractEventHasAccessors"> <source>'{0}': abstract event cannot use event accessor syntax</source> <target state="translated">{0}: abstraktní událost nemůže používat syntaxi přístupového objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfMethodGroupInExpressionTree"> <source>'&amp;' on method groups cannot be used in expression trees</source> <target state="translated">&amp; pro skupiny metod se nedá použít ve stromech výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_AddressOfToNonFunctionPointer"> <source>Cannot convert &amp;method group '{0}' to non-function pointer type '{1}'.</source> <target state="translated">Skupina &amp;method {0} se nedá převést na typ ukazatele, který neukazuje na funkci ({1}).</target> <note /> </trans-unit> <trans-unit id="ERR_AltInterpolatedVerbatimStringsNotAvailable"> <source>To use '@$' instead of '$@' for an interpolated verbatim string, please use language version '{0}' or greater.</source> <target state="translated">Pokud chcete pro interpolovaný doslovný řetězec použít @$ místo $@, použijte verzi jazyka {0} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOpsOnDefault"> <source>Operator '{0}' is ambiguous on operands '{1}' and '{2}'</source> <target state="translated">Operátor {0} je na operandech {1} a {2} nejednoznačný.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOpsOnUnconstrainedDefault"> <source>Operator '{0}' cannot be applied to 'default' and operand of type '{1}' because it is a type parameter that is not known to be a reference type</source> <target state="translated">Operátor {0} nejde použít pro default a operand typu {1}, protože se jedná o parametr typu, který není znám jako odkazový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AnnotationDisallowedInObjectCreation"> <source>Cannot use a nullable reference type in object creation.</source> <target state="translated">K vytvoření objektu nejde použít typ odkazu s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_ArgumentNameInITuplePattern"> <source>Element names are not permitted when pattern-matching via 'System.Runtime.CompilerServices.ITuple'.</source> <target state="translated">Názvy elementů nejsou povolené při porovnávání vzorů přes System.Runtime.CompilerServices.ITuple.</target> <note /> </trans-unit> <trans-unit id="ERR_AsNullableType"> <source>It is not legal to use nullable reference type '{0}?' in an as expression; use the underlying type '{0}' instead.</source> <target state="translated">Ve výrazu as se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignmentInitOnly"> <source>Init-only property or indexer '{0}' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.</source> <target state="translated">Vlastnost jenom pro inicializaci nebo indexer {0} se dá přiřadit jenom k inicializátoru objektu, pomocí klíčového slova this nebo base v konstruktoru instance nebo k přístupovému objektu init.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrDependentTypeNotAllowed"> <source>Type '{0}' cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type '{0}' cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrTypeArgCannotBeTypeVar"> <source>'{0}': an attribute type argument cannot use type parameters</source> <target state="new">'{0}': an attribute type argument cannot use type parameters</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeNotOnEventAccessor"> <source>Attribute '{0}' is not valid on event accessors. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro přístupové objekty události. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributesRequireParenthesizedLambdaExpression"> <source>Attributes on lambda expressions require a parenthesized parameter list.</source> <target state="new">Attributes on lambda expressions require a parenthesized parameter list.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyWithSetterCantBeReadOnly"> <source>Auto-implemented property '{0}' cannot be marked 'readonly' because it has a 'set' accessor.</source> <target state="translated">Automaticky implementovanou vlastnost {0} nelze označit modifikátorem readonly, protože má přístupový objekt set.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoSetterCantBeReadOnly"> <source>Auto-implemented 'set' accessor '{0}' cannot be marked 'readonly'.</source> <target state="translated">Automaticky implementovaný přístupový objekt set {0} nelze označit modifikátorem readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitForEachMissingMember"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a suitable public instance or extension definition for '{1}'</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje vhodnou veřejnou definici instance nebo rozšíření pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitForEachMissingMemberWrongAsync"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'foreach' rather than 'await foreach'?</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu foreach místo await foreach?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractBinaryOperatorSignature"> <source>One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractIncDecRetType"> <source>The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter.</source> <target state="new">The return type for ++ or -- operator must either match the parameter type, or be derived from the parameter type, or be the containing type's type parameter constrained to it unless the parameter type is a different type parameter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractIncDecSignature"> <source>The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">The parameter type for ++ or -- operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractShiftOperatorSignature"> <source>The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int</source> <target state="new">The first operand of an overloaded shift operator must have the same type as the containing type or its type parameter constrained to it, and the type of the second operand must be int</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractStaticMemberAccess"> <source>A static abstract interface member can be accessed only on a type parameter.</source> <target state="new">A static abstract interface member can be accessed only on a type parameter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAbstractUnaryOperatorSignature"> <source>The parameter of a unary operator must be the containing type, or its type parameter constrained to it.</source> <target state="new">The parameter of a unary operator must be the containing type, or its type parameter constrained to it.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerArgumentExpressionParamWithoutDefaultValue"> <source>The CallerArgumentExpressionAttribute may only be applied to parameters with default values</source> <target state="new">The CallerArgumentExpressionAttribute may only be applied to parameters with default values</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicAwaitForEach"> <source>Cannot use a collection of dynamic type in an asynchronous foreach</source> <target state="translated">V asynchronním příkazu foreach nejde použít kolekce dynamického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFieldTypeInRecord"> <source>The type '{0}' may not be used for a field of a record.</source> <target state="translated">Typ {0} se nedá použít pro pole záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFuncPointerArgCount"> <source>Function pointer '{0}' does not take {1} arguments</source> <target state="translated">Ukazatel na funkci {0} nepřijímá tento počet argumentů: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadFuncPointerParamModifier"> <source>'{0}' cannot be used as a modifier on a function pointer parameter.</source> <target state="translated">{0} se nedá použít jako modifikátor v parametru ukazatele na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInheritanceFromRecord"> <source>Only records may inherit from records.</source> <target state="translated">Ze záznamů můžou dědit jenom záznamy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInitAccessor"> <source>The 'init' accessor is not valid on static members</source> <target state="translated">Přístupový objekt init není platný pro statické členy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullableContextOption"> <source>Invalid option '{0}' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'</source> <target state="translated">Neplatná možnost {0} pro /nullable. Je třeba použít disable, enable, warnings nebo annotations.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNullableTypeof"> <source>The typeof operator cannot be used on a nullable reference type</source> <target state="translated">Operátor typeof nejde použít na typ odkazů s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_BadOpOnNullOrDefaultOrNew"> <source>Operator '{0}' cannot be applied to operand '{1}'</source> <target state="translated">Operátor {0} nejde použít pro operand {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPatternExpression"> <source>Invalid operand for pattern match; value required, but found '{0}'.</source> <target state="translated">Neplatný operand pro porovnávací vzorek. Vyžaduje se hodnota, ale nalezeno: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordBase"> <source>Records may only inherit from object or another record</source> <target state="translated">Záznamy můžou dědit jenom z objektu nebo jiného záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRecordMemberForPositionalParameter"> <source>Record member '{0}' must be a readable instance property or field of type '{1}' to match positional parameter '{2}'.</source> <target state="needs-review-translation">Člen záznamu {0} musí být čitelná vlastnost instance typu {1}, která se bude shodovat s pozičním parametrem {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitchValue"> <source>Command-line syntax error: '{0}' is not a valid value for the '{1}' option. The value must be of the form '{2}'.</source> <target state="translated">Chyba syntaxe příkazového řádku: {0} není platná hodnota možnosti {1}. Hodnota musí mít tvar {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BuilderAttributeDisallowed"> <source>The AsyncMethodBuilder attribute is disallowed on anonymous methods without an explicit return type.</source> <target state="new">The AsyncMethodBuilder attribute is disallowed on anonymous methods without an explicit return type.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotClone"> <source>The receiver type '{0}' is not a valid record type and is not a struct type.</source> <target state="new">The receiver type '{0}' is not a valid record type and is not a struct type.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotConvertAddressOfToDelegate"> <source>Cannot convert &amp;method group '{0}' to delegate type '{0}'.</source> <target state="translated">Skupina &amp;metody {0} se nedá převést na typ delegáta {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotInferDelegateType"> <source>The delegate type could not be inferred.</source> <target state="new">The delegate type could not be inferred.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotSpecifyManagedWithUnmanagedSpecifiers"> <source>'managed' calling convention cannot be combined with unmanaged calling convention specifiers.</source> <target state="translated">Konvence volání managed se nedá kombinovat se specifikátory konvence nespravovaného volání.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseFunctionPointerAsFixedLocal"> <source>The type of a local declared in a fixed statement cannot be a function pointer type.</source> <target state="translated">Lokální proměnná deklarovaná v příkazu fixed nemůže být typu ukazatel na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseManagedTypeInUnmanagedCallersOnly"> <source>Cannot use '{0}' as a {1} type on a method attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">V metodě, která má atribut UnmanagedCallersOnly, se nedá jako typ {1} použít {0}.</target> <note>1 is the localized word for 'parameter' or 'return'. UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_CannotUseReducedExtensionMethodInAddressOf"> <source>Cannot use an extension method with a receiver as the target of a '&amp;' operator.</source> <target state="translated">Rozšiřující metoda, kde jako cíl je nastavený příjemce, se nedá použít jako cíl operátoru &amp;.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotUseSelfAsInterpolatedStringHandlerArgument"> <source>InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.</source> <target state="new">InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on.</target> <note>InterpolatedStringHandlerArgumentAttribute is a type name and should not be translated.</note> </trans-unit> <trans-unit id="ERR_CantChangeInitOnlyOnOverride"> <source>'{0}' must match by init-only of overridden member '{1}'</source> <target state="translated">{0} musí odpovídat vlastnosti jenom pro inicializaci přepsaného člena {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethReturnType"> <source>Cannot convert {0} to type '{1}' because the return type does not match the delegate return type</source> <target state="new">Cannot convert {0} to type '{1}' because the return type does not match the delegate return type</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseInOrOutInArglist"> <source>__arglist cannot have an argument passed by 'in' or 'out'</source> <target state="translated">__arglist nemůže mít argument předávaný pomocí in nebo out</target> <note /> </trans-unit> <trans-unit id="ERR_CloneDisallowedInRecord"> <source>Members named 'Clone' are disallowed in records.</source> <target state="translated">Členy s názvem Clone se v záznamech nepovolují.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberNotStatic"> <source>'{0}' does not implement static interface member '{1}'. '{2}' cannot implement the interface member because it is not static.</source> <target state="new">'{0}' does not implement static interface member '{1}'. '{2}' cannot implement the interface member because it is not static.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongInitOnly"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}'.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConWithUnmanagedCon"> <source>Type parameter '{1}' has the 'unmanaged' constraint so '{1}' cannot be used as a constraint for '{0}'</source> <target state="translated">Parametr typu {1} má omezení unmanaged, takže není možné používat {1} jako omezení pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnLocalFunction"> <source>Local function '{0}' must be 'static' in order to use the Conditional attribute</source> <target state="translated">Aby bylo možné používat atribut Conditional, musí být místní funkce {0} static.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantPatternVsOpenType"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}'. Please use language version '{2}' or greater to match an open type with a constant pattern.</source> <target state="translated">Výraz typu {0} nelze zpracovat vzorem typu {1}. Použijte prosím verzi jazyka {2} nebo vyšší, aby odpovídala otevřenému typu se vzorem konstanty.</target> <note /> </trans-unit> <trans-unit id="ERR_CopyConstructorMustInvokeBaseCopyConstructor"> <source>A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.</source> <target state="translated">Kopírovací konstruktor v záznamu musí volat kopírovací konstruktor základní třídy, případně konstruktor objektu bez parametrů, pokud záznam dědí z objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_CopyConstructorWrongAccessibility"> <source>A copy constructor '{0}' must be public or protected because the record is not sealed.</source> <target state="translated">Kopírovací konstruktor {0} musí být veřejný nebo chráněný, protože záznam není zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructParameterNameMismatch"> <source>The name '{0}' does not match the corresponding 'Deconstruct' parameter '{1}'.</source> <target state="translated">Název {0} neodpovídá příslušnému parametru Deconstruct {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultConstraintOverrideOnly"> <source>The 'default' constraint is valid on override and explicit interface implementation methods only.</source> <target state="translated">Omezení default je platné jen v přepsaných metodách a metodách explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultInterfaceImplementationInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a non-abstract member. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má neabstraktní člen. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultLiteralNoTargetType"> <source>There is no target type for the default literal.</source> <target state="translated">Není k dispozici žádný cílový typ pro výchozí literál.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultPattern"> <source>A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'.</source> <target state="translated">Výchozí literál default není platný jako vzor. Podle potřeby použijte jiný literál (například 0 nebo null). Pokud chcete, aby odpovídalo vše, použijte vzor discard „_“.</target> <note /> </trans-unit> <trans-unit id="ERR_DesignatorBeneathPatternCombinator"> <source>A variable may not be declared within a 'not' or 'or' pattern.</source> <target state="translated">Proměnná se nedá deklarovat ve vzoru not nebo or.</target> <note /> </trans-unit> <trans-unit id="ERR_DiscardPatternInSwitchStatement"> <source>The discard pattern is not permitted as a case label in a switch statement. Use 'case var _:' for a discard pattern, or 'case @_:' for a constant named '_'.</source> <target state="translated">Tento vzor discard není povolený jako návěstí příkazu case v příkazu switch. Použijte „case var _:“ pro vzor discard nebo „case @_:“ pro konstantu s názvem „_“.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideBaseEqualityContract"> <source>'{0}' does not override expected property from '{1}'.</source> <target state="translated">{0} nepřepisuje očekávanou vlastnost z {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideBaseMethod"> <source>'{0}' does not override expected method from '{1}'.</source> <target state="translated">{0} nepřepisuje očekávanou metodu z {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesNotOverrideMethodFromObject"> <source>'{0}' does not override expected method from 'object'.</source> <target state="translated">{0} nepřepisuje očekávanou metodu z object.</target> <note /> </trans-unit> <trans-unit id="ERR_DupReturnTypeMod"> <source>A return type can only have one '{0}' modifier.</source> <target state="translated">Návratový typ může mít jen jeden modifikátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateExplicitImpl"> <source>'{0}' is explicitly implemented more than once.</source> <target state="translated">Položka {0} je explicitně implementována více než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceWithDifferencesInBaseList"> <source>'{0}' is already listed in the interface list on type '{2}' as '{1}'.</source> <target state="translated">{0} je již uvedeno v seznamu rozhraní u typu {2} jako {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNullSuppression"> <source>Duplicate null suppression operator ('!')</source> <target state="translated">Duplicitní operátor potlačení hodnoty null (!)</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyReadOnlyMods"> <source>Cannot specify 'readonly' modifiers on both accessors of property or indexer '{0}'. Instead, put a 'readonly' modifier on the property itself.</source> <target state="translated">Pro přístupové objekty vlastnosti i indexeru {0} nelze zadat modifikátory readonly. Místo toho zadejte modifikátor readonly jenom pro vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_ElseCannotStartStatement"> <source>'else' cannot start a statement.</source> <target state="translated">Příkaz nemůže začínat na else.</target> <note /> </trans-unit> <trans-unit id="ERR_EntryPointCannotBeUnmanagedCallersOnly"> <source>Application entry points cannot be attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">Vstupní body aplikací nemůžou mít atribut UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_EqualityContractRequiresGetter"> <source>Record equality contract property '{0}' must have a get accessor.</source> <target state="translated">Vlastnost kontraktu rovnosti záznamu {0} musí mít přístupový objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplementationOfOperatorsMustBeStatic"> <source>Explicit implementation of a user-defined operator '{0}' must be declared static</source> <target state="new">Explicit implementation of a user-defined operator '{0}' must be declared static</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitNullableAttribute"> <source>Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.</source> <target state="translated">Explicitní použití System.Runtime.CompilerServices.NullableAttribute není povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyMismatchInitOnly"> <source>Accessors '{0}' and '{1}' should both be init-only or neither</source> <target state="translated">Přístupové objekty {0} a {1} by měly být buď oba jenom pro inicializaci, nebo ani jeden.</target> <note /> </trans-unit> <trans-unit id="ERR_ExprCannotBeFixed"> <source>The given expression cannot be used in a fixed statement</source> <target state="translated">Daný výraz nelze použít v příkazu fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeCantContainNullCoalescingAssignment"> <source>An expression tree may not contain a null coalescing assignment</source> <target state="translated">Strom výrazu nesmí obsahovat přiřazení představující sloučení s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeCantContainRefStruct"> <source>Expression tree cannot contain value of ref struct or restricted type '{0}'.</source> <target state="translated">Strom výrazu nemůže obsahovat hodnotu struktury REF ani zakázaný typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAbstractStaticMemberAccess"> <source>An expression tree may not contain an access of static abstract interface member</source> <target state="new">An expression tree may not contain an access of static abstract interface member</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsFromEndIndexExpression"> <source>An expression tree may not contain a from-end index ('^') expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz indexu od-do (^).</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion"> <source>An expression tree may not contain an interpolated string handler conversion.</source> <target state="new">An expression tree may not contain an interpolated string handler conversion.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer"> <source>An expression tree may not contain a pattern System.Index or System.Range indexer access</source> <target state="translated">Strom výrazů možná neobsahuje vzor přístupu indexeru System.Index nebo System.Range.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsRangeExpression"> <source>An expression tree may not contain a range ('..') expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz rozsahu (..).</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsSwitchExpression"> <source>An expression tree may not contain a switch expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz switch.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleBinOp"> <source>An expression tree may not contain a tuple == or != operator</source> <target state="translated">Strom výrazů nesmí obsahovat operátor řazené kolekce členů == nebo !=.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsWithExpression"> <source>An expression tree may not contain a with-expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz with.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternEventInitializer"> <source>'{0}': extern event cannot have initializer</source> <target state="translated">{0}: Externí událost nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureInPreview"> <source>The feature '{0}' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version.</source> <target state="translated">Funkce {0} je aktuálně ve verzi Preview a je *nepodporovaná*. Pokud chcete používat funkce Preview, použijte jazykovou verzi preview.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureIsExperimental"> <source>Feature '{0}' is experimental and unsupported; use '/features:{1}' to enable.</source> <target state="translated">Funkce {0} je zkušební, a proto není podporovaná. K aktivaci použijte /features:{1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion10"> <source>Feature '{0}' is not available in C# 10.0. Please use language version {1} or greater.</source> <target state="new">Feature '{0}' is not available in C# 10.0. Please use language version {1} or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion8"> <source>Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion8_0"> <source>Feature '{0}' is not available in C# 8.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 8.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion9"> <source>Feature '{0}' is not available in C# 9.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není v C# 9.0 dostupná. Použijte prosím jazykovou verzi {1} nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldLikeEventCantBeReadOnly"> <source>Field-like event '{0}' cannot be 'readonly'.</source> <target state="translated">Událost podobná poli {0} nemůže mít modifikátor readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_FileScopedAndNormalNamespace"> <source>Source file can not contain both file-scoped and normal namespace declarations.</source> <target state="new">Source file can not contain both file-scoped and normal namespace declarations.</target> <note /> </trans-unit> <trans-unit id="ERR_FileScopedNamespaceNotBeforeAllMembers"> <source>File-scoped namespace must precede all other members in a file.</source> <target state="new">File-scoped namespace must precede all other members in a file.</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachMissingMemberWrongAsync"> <source>foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'. Did you mean 'await foreach' rather than 'foreach'?</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}. Měli jste v úmyslu await foreach místo foreach?</target> <note /> </trans-unit> <trans-unit id="ERR_FuncPtrMethMustBeStatic"> <source>Cannot create a function pointer for '{0}' because it is not a static method</source> <target state="translated">Pro {0} se nedá vytvořit ukazatel na funkci, protože to není statická metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_FuncPtrRefMismatch"> <source>Ref mismatch between '{0}' and function pointer '{1}'</source> <target state="translated">Mezi {0} a ukazatelem na funkci {1} se neshoduje odkaz.</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionPointerTypesInAttributeNotSupported"> <source>Using a function pointer type in a 'typeof' in an attribute is not supported.</source> <target state="needs-review-translation">V typeof v atributu se nepodporuje používání typu ukazatele funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_FunctionPointersCannotBeCalledWithNamedArguments"> <source>A function pointer cannot be called with named arguments.</source> <target state="translated">Ukazatel na funkci se nedá zavolat s pojmenovanými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers"> <source>The interface '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The constraint interface '{1}' or its base interface has static abstract members.</source> <target state="new">The interface '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The constraint interface '{1}' or its base interface has static abstract members.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalUsingInNamespace"> <source>A global using directive cannot be used in a namespace declaration.</source> <target state="new">A global using directive cannot be used in a namespace declaration.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalUsingOutOfOrder"> <source>A global using directive must precede all non-global using directives.</source> <target state="new">A global using directive must precede all non-global using directives.</target> <note /> </trans-unit> <trans-unit id="ERR_GoToBackwardJumpOverUsingVar"> <source>A goto cannot jump to a location before a using declaration within the same block.</source> <target state="translated">Příkaz goto nemůže přejít na místo před deklarací using ve stejném bloku.</target> <note /> </trans-unit> <trans-unit id="ERR_GoToForwardJumpOverUsingVar"> <source>A goto cannot jump to a location after a using declaration.</source> <target state="translated">Příkaz goto nemůže přejít na místo za deklarací using.</target> <note /> </trans-unit> <trans-unit id="ERR_HiddenPositionalMember"> <source>The positional member '{0}' found corresponding to this parameter is hidden.</source> <target state="translated">Poziční člen {0}, který odpovídá tomuto parametru je skrytý.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalSuppression"> <source>The suppression operator is not allowed in this context</source> <target state="translated">Operátor potlačení není v tomto kontextu povolený.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitIndexIndexerWithName"> <source>Invocation of implicit Index Indexer cannot name the argument.</source> <target state="translated">Volání implicitního indexeru indexů nemůže pojmenovat argument.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationIllegalTargetType"> <source>The type '{0}' may not be used as the target type of new()</source> <target state="translated">Typ {0} se nedá použít jako cílový typ příkazu new().</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationNoTargetType"> <source>There is no target type for '{0}'</source> <target state="translated">Není k dispozici žádný cílový typ pro {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitObjectCreationNotValid"> <source>Use of new() is not valid in this context</source> <target state="translated">Použití new() není v tomto kontextu platné</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitRangeIndexerWithName"> <source>Invocation of implicit Range Indexer cannot name the argument.</source> <target state="translated">Volání implicitního indexeru rozsahů nemůže pojmenovat argument.</target> <note /> </trans-unit> <trans-unit id="ERR_InDynamicMethodArg"> <source>Arguments with 'in' modifier cannot be used in dynamically dispatched expressions.</source> <target state="translated">Argumenty s modifikátorem in se nedají použít v dynamicky volaných výrazech.</target> <note /> </trans-unit> <trans-unit id="ERR_InheritingFromRecordWithSealedToString"> <source>Inheriting from a record with a sealed 'Object.ToString' is not supported in C# {0}. Please use language version '{1}' or greater.</source> <target state="translated">Dědění ze záznamu se zapečetěným objektem Object.ToString se v jazyce C# {0} nepodporuje. Použijte prosím jazykovou verzi {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_InitCannotBeReadonly"> <source>'init' accessors cannot be marked 'readonly'. Mark '{0}' readonly instead.</source> <target state="translated">Přístupové objekty init se nedají označit jako jen pro čtení. Místo toho označte jako jen pro čtení {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InstancePropertyInitializerInInterface"> <source>Instance properties in interfaces cannot have initializers.</source> <target state="translated">Vlastnosti instance v rozhraních nemůžou mít inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod"> <source>'UnmanagedCallersOnly' method '{0}' cannot implement interface member '{1}' in type '{2}'</source> <target state="new">'UnmanagedCallersOnly' method '{0}' cannot implement interface member '{1}' in type '{2}'</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_InterfaceImplementedImplicitlyByVariadic"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because it has an __arglist parameter</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože má parametr __arglist.</target> <note /> </trans-unit> <trans-unit id="ERR_InternalError"> <source>Internal error in the C# compiler.</source> <target state="translated">Vnitřní chyba v kompilátoru jazyka C#</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentAttributeMalformed"> <source>The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.</source> <target state="new">The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually.</target> <note>InterpolatedStringHandlerArgumentAttribute is a type name and should not be translated.</note> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString"> <source>Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.</source> <target state="new">Parameter '{0}' is an argument to the interpolated string handler conversion on parameter '{1}', but the corresponding argument is specified after the interpolated string expression. Reorder the arguments to move '{0}' before '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified"> <source>Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.</source> <target state="new">Parameter '{0}' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter '{1}'. Specify the value of '{0}' before '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerCreationCannotUseDynamic"> <source>An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.</source> <target state="new">An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerMethodReturnInconsistent"> <source>Interpolated string handler method '{0}' has inconsistent return type. Expected to return '{1}'.</source> <target state="new">Interpolated string handler method '{0}' has inconsistent return type. Expected to return '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InterpolatedStringHandlerMethodReturnMalformed"> <source>Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.</source> <target state="new">Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'.</target> <note>void and bool are keywords</note> </trans-unit> <trans-unit id="ERR_InvalidFuncPointerReturnTypeModifier"> <source>'{0}' is not a valid function pointer return type modifier. Valid modifiers are 'ref' and 'ref readonly'.</source> <target state="translated">{0} není platný modifikátor návratového typu ukazatele na funkci. Platné modifikátory jsou ref a ref readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFunctionPointerCallingConvention"> <source>'{0}' is not a valid calling convention specifier for a function pointer.</source> <target state="translated">{0} není platný specifikátor konvence volání pro ukazatel na funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidHashAlgorithmName"> <source>Invalid hash algorithm name: '{0}'</source> <target state="translated">Neplatný název algoritmu hash: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInterpolatedStringHandlerArgumentName"> <source>'{0}' is not a valid parameter name from '{1}'.</source> <target state="new">'{0}' is not a valid parameter name from '{1}'.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidModifierForLanguageVersion"> <source>The modifier '{0}' is not valid for this item in C# {1}. Please use language version '{2}' or greater.</source> <target state="translated">Modifikátor {0} není platný pro tuto položku v jazyce C# {1}. Použijte prosím verzi jazyka {2} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNameInSubpattern"> <source>Identifier or a simple member access expected.</source> <target state="new">Identifier or a simple member access expected.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidObjectCreation"> <source>Invalid object creation</source> <target state="translated">Vytvoření neplatného objektu</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPropertyReadOnlyMods"> <source>Cannot specify 'readonly' modifiers on both property or indexer '{0}' and its accessor. Remove one of them.</source> <target state="translated">Pro vlastnost nebo indexer {0} i jejich přístupový objekt nelze zadat modifikátory readonly. Odeberte jeden z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidStackAllocArray"> <source>"Invalid rank specifier: expected ']'</source> <target state="translated">Specifikátor rozsahu je neplatný. Očekávala se pravá hranatá závorka ].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidUnmanagedCallersOnlyCallConv"> <source>'{0}' is not a valid calling convention type for 'UnmanagedCallersOnly'.</source> <target state="translated">{0} není platný typ konvence volání pro UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_InvalidWithReceiverType"> <source>The receiver of a `with` expression must have a non-void type.</source> <target state="translated">Příjemce výrazu with musí mít neprázdný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_IsNullableType"> <source>It is not legal to use nullable reference type '{0}?' in an is-type expression; use the underlying type '{0}' instead.</source> <target state="translated">Ve výrazu is-type se nepovoluje použití typu odkazu s možnou hodnotou null {0}?; místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_IsPatternImpossible"> <source>An expression of type '{0}' can never match the provided pattern.</source> <target state="translated">Výraz typu {0} nesmí nikdy odpovídat poskytnutému vzoru.</target> <note /> </trans-unit> <trans-unit id="ERR_IteratorMustBeAsync"> <source>Method '{0}' with an iterator block must be 'async' to return '{1}'</source> <target state="translated">Metoda {0} s blokem iterátoru musí být asynchronní, aby vrátila {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaWithAttributesToExpressionTree"> <source>A lambda expression with attributes cannot be converted to an expression tree</source> <target state="new">A lambda expression with attributes cannot be converted to an expression tree</target> <note /> </trans-unit> <trans-unit id="ERR_LineSpanDirectiveEndLessThanStart"> <source>The #line directive end position must be greater than or equal to the start position</source> <target state="new">The #line directive end position must be greater than or equal to the start position</target> <note /> </trans-unit> <trans-unit id="ERR_LineSpanDirectiveInvalidValue"> <source>The #line directive value is missing or out of range</source> <target state="new">The #line directive value is missing or out of range</target> <note /> </trans-unit> <trans-unit id="ERR_MethFuncPtrMismatch"> <source>No overload for '{0}' matches function pointer '{1}'</source> <target state="translated">Žádná přetížená metoda {0} neodpovídá ukazateli na funkci {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingAddressOf"> <source>Cannot convert method group to function pointer (Are you missing a '&amp;'?)</source> <target state="translated">Skupina metod se nedá převést na ukazatel na funkci (nechybí &amp;)?</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPattern"> <source>Pattern missing</source> <target state="translated">Chybějící vzor</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerCannotBeUnmanagedCallersOnly"> <source>Module initializer cannot be attributed with 'UnmanagedCallersOnly'.</source> <target state="translated">Inicializátor modulu nemůže mít atribut UnmanagedCallersOnly.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric"> <source>Module initializer method '{0}' must not be generic and must not be contained in a generic type</source> <target state="translated">Inicializační metoda modulu {0} nemůže být obecná a nesmí obsahovat obecný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType"> <source>Module initializer method '{0}' must be accessible at the module level</source> <target state="translated">Inicializační metoda modulu {0} musí být přístupná na úrovni modulu.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeOrdinary"> <source>A module initializer must be an ordinary member method</source> <target state="translated">Inicializátor modulu musí být běžná členská metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid"> <source>Module initializer method '{0}' must be static, must have no parameters, and must return 'void'</source> <target state="translated">Inicializační metoda modulu {0} musí být statická, nesmí mít žádné parametry a musí vracet void.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleAnalyzerConfigsInSameDir"> <source>Multiple analyzer config files cannot be in the same directory ('{0}').</source> <target state="translated">Ve stejném adresáři nemůže být více konfiguračních souborů analyzátoru ({0}).</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEnumeratorCancellationAttributes"> <source>The attribute [EnumeratorCancellation] cannot be used on multiple parameters</source> <target state="translated">Atribut [EnumeratorCancellation] nejde použít na víc parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleFileScopedNamespace"> <source>Source file can only contain one file-scoped namespace declaration.</source> <target state="new">Source file can only contain one file-scoped namespace declaration.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleRecordParameterLists"> <source>Only a single record partial declaration may have a parameter list</source> <target state="translated">Seznam parametrů může mít jenom částečná deklarace jednoho záznamu.</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundWithUnmanaged"> <source>The 'new()' constraint cannot be used with the 'unmanaged' constraint</source> <target state="translated">Omezení new() nejde používat s omezením unmanaged.</target> <note /> </trans-unit> <trans-unit id="ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString"> <source>Newlines are not allowed inside a non-verbatim interpolated string</source> <target state="new">Newlines are not allowed inside a non-verbatim interpolated string</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIAsyncDispWrongAsync"> <source>'{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method. Did you mean 'using' rather than 'await using'?</source> <target state="translated">{0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync. Měli jste v úmyslu použít using nebo await using?</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIDispWrongAsync"> <source>'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'?</source> <target state="translated">{0}: Typ použitý v příkazu using musí být implicitně převoditelný na System.IDisposable. Neměli jste v úmyslu použít await using místo using?</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerArgumentExpressionParam"> <source>CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="new">CallerArgumentExpressionAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</target> <note /> </trans-unit> <trans-unit id="ERR_NoCopyConstructorInBaseType"> <source>No accessible copy constructor found in base type '{0}'.</source> <target state="translated">V základním typu {0} se nenašel žádný přístupný kopírovací konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConvTargetTypedConditional"> <source>Conditional expression is not valid in language version {0} because a common type was not found between '{1}' and '{2}'. To use a target-typed conversion, upgrade to language version {3} or greater.</source> <target state="new">Conditional expression is not valid in language version {0} because a common type was not found between '{1}' and '{2}'. To use a target-typed conversion, upgrade to language version {3} or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_NoOutputDirectory"> <source>Output directory could not be determined</source> <target state="translated">Nepovedlo se určit výstupní adresář.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPrivateAPIInRecord"> <source>Record member '{0}' must be private.</source> <target state="translated">Člen záznamu {0} musí být privátní.</target> <note /> </trans-unit> <trans-unit id="ERR_NonProtectedAPIInRecord"> <source>Record member '{0}' must be protected.</source> <target state="translated">Člen záznamu {0} musí být chráněný.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPublicAPIInRecord"> <source>Record member '{0}' must be public.</source> <target state="translated">Člen záznamu {0} musí být veřejný.</target> <note /> </trans-unit> <trans-unit id="ERR_NonPublicParameterlessStructConstructor"> <source>The parameterless struct constructor must be 'public'.</source> <target state="new">The parameterless struct constructor must be 'public'.</target> <note /> </trans-unit> <trans-unit id="ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName"> <source>'{0}' is not an instance method, the receiver cannot be an interpolated string handler argument.</source> <target state="new">'{0}' is not an instance method, the receiver cannot be an interpolated string handler argument.</target> <note /> </trans-unit> <trans-unit id="ERR_NotOverridableAPIInRecord"> <source>'{0}' must allow overriding because the containing record is not sealed.</source> <target state="translated">{0} musí povolovat přepisování, protože obsahující záznam není zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_NullInvalidInterpolatedStringHandlerArgumentName"> <source>null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.</source> <target state="new">null is not a valid parameter name. To get access to the receiver of an instance method, use the empty string as the parameter name.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDirectiveQualifierExpected"> <source>Expected 'enable', 'disable', or 'restore'</source> <target state="translated">Očekávala se hodnota enable, disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableDirectiveTargetExpected"> <source>Expected 'warnings', 'annotations', or end of directive</source> <target state="translated">Očekávala se možnost warnings nebo annotations nebo konec direktivy.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableOptionNotAvailable"> <source>Invalid '{0}' value: '{1}' for C# {2}. Please use language version '{3}' or greater.</source> <target state="translated">Neplatná hodnota {0}: {1} pro jazyk C# {2}. Použijte prosím verzi jazyka {3} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_NullableUnconstrainedTypeParameter"> <source>A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '{0}' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint.</source> <target state="translated">Pokud se nepoužívá verze jazyka {0} nebo novější, musí být pro parametr typu s možnou hodnotou null známo, že má typ hodnoty nebo typ odkazu, který není možné nastavit na null. Zvažte možnost změnit verzi jazyka nebo přidat class, struct nebo omezení typu.</target> <note /> </trans-unit> <trans-unit id="ERR_OmittedTypeArgument"> <source>Omitting the type argument is not allowed in the current context</source> <target state="translated">V aktuálním kontextu se vynechání argumentu typu nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_OutVariableCannotBeByRef"> <source>An out variable cannot be declared as a ref local</source> <target state="translated">Výstupní proměnná nemůže být deklarovaná jako lokální proměnná podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideDefaultConstraintNotSatisfied"> <source>Method '{0}' specifies a 'default' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is constrained to a reference type or a value type.</source> <target state="translated">Metoda {0} určuje omezení default pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není omezený na typ odkazu nebo hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideRefConstraintNotSatisfied"> <source>Method '{0}' specifies a 'class' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a reference type.</source> <target state="translated">Metoda {0} určuje omezení class pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není odkazový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideValConstraintNotSatisfied"> <source>Method '{0}' specifies a 'struct' constraint for type parameter '{1}', but corresponding type parameter '{2}' of overridden or explicitly implemented method '{3}' is not a non-nullable value type.</source> <target state="translated">Metoda {0} určuje omezení struct pro parametr typu {1}, ale odpovídající parametr typu {2} přepsané nebo explicitně implementované metody {3} není typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodAccessibilityDifference"> <source>Both partial method declarations must have identical accessibility modifiers.</source> <target state="translated">Obě deklarace částečných metod musí mít shodné modifikátory přístupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodExtendedModDifference"> <source>Both partial method declarations must have identical combinations of 'virtual', 'override', 'sealed', and 'new' modifiers.</source> <target state="translated">Obě deklarace částečných metod musí mít shodné kombinace modifikátorů virtual, override, sealed a new.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodReadOnlyDifference"> <source>Both partial method declarations must be readonly or neither may be readonly</source> <target state="translated">Obě deklarace částečné metody musí mít modifikátor readonly, nebo nesmí mít modifikátor readonly žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodRefReturnDifference"> <source>Partial method declarations must have matching ref return values.</source> <target state="translated">Deklarace částečných metod musí mít odpovídající referenční návratové hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodReturnTypeDifference"> <source>Both partial method declarations must have the same return type.</source> <target state="translated">Obě deklarace částečných metod musí mít stejný návratový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithAccessibilityModsMustHaveImplementation"> <source>Partial method '{0}' must have an implementation part because it has accessibility modifiers.</source> <target state="translated">Částečná metoda {0} musí mít implementační část, protože má modifikátory přístupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithExtendedModMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má modifikátor virtual, override, sealed, new nebo extern.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has a non-void return type.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má návratový typ jiný než void.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodWithOutParamMustHaveAccessMods"> <source>Partial method '{0}' must have accessibility modifiers because it has 'out' parameters.</source> <target state="translated">Částečná metoda {0} musí mít modifikátory přístupnosti, protože má parametry out.</target> <note /> </trans-unit> <trans-unit id="ERR_PointerTypeInPatternMatching"> <source>Pattern-matching is not permitted for pointer types.</source> <target state="translated">Porovnávání vzorů není povolené pro typy ukazatelů.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleAsyncIteratorWithoutYield"> <source>The body of an async-iterator method must contain a 'yield' statement.</source> <target state="translated">Tělo metody async-iterator musí obsahovat příkaz yield.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleAsyncIteratorWithoutYieldOrAwait"> <source>The body of an async-iterator method must contain a 'yield' statement. Consider removing 'async' from the method declaration or adding a 'yield' statement.</source> <target state="translated">Tělo metody async-iterator musí obsahovat příkaz yield. Zvažte odebrání položky async z deklarace metody nebo přidání příkazu yield.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyPatternNameMissing"> <source>A property subpattern requires a reference to the property or field to be matched, e.g. '{{ Name: {0} }}'</source> <target state="translated">Dílčí vzor vlastnosti vyžaduje odkaz na vlastnost nebo pole k přiřazení, např. „{{ Name: {0} }}“.</target> <note /> </trans-unit> <trans-unit id="ERR_ReAbstractionInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a re-abstraction of a member from base interface. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má reabstrakci člena ze základního rozhraní. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_ReadOnlyModMissingAccessor"> <source>'{0}': 'readonly' can only be used on accessors if the property or indexer has both a get and a set accessor</source> <target state="translated">{0}: U přístupových objektů se modifikátor readonly může použít jenom v případě, že vlastnost nebo indexer má přístupový objekt get i set.</target> <note /> </trans-unit> <trans-unit id="ERR_RecordAmbigCtor"> <source>The primary constructor conflicts with the synthesized copy constructor.</source> <target state="translated">Primární konstruktor je v konfliktu se syntetizovaně zkopírovaným konstruktorem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefAssignNarrower"> <source>Cannot ref-assign '{1}' to '{0}' because '{1}' has a narrower escape scope than '{0}'.</source> <target state="translated">Přiřazení odkazu {1} k {0} nelze provést, protože {1} má užší řídicí obor než {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefLocalOrParamExpected"> <source>The left-hand side of a ref assignment must be a ref local or parameter.</source> <target state="translated">Levá strana přiřazení odkazu musí být lokální proměnná nebo parametr odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RelationalPatternWithNaN"> <source>Relational patterns may not be used for a floating-point NaN.</source> <target state="translated">Relační vzory se nedají použít pro hodnotu Není číslo s plovoucí desetinnou čárkou.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses"> <source>'{0}': Target runtime doesn't support covariant types in overrides. Type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Cílový modul runtime nepodporuje v přepisech kovariantní typy. Typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses"> <source>'{0}': Target runtime doesn't support covariant return types in overrides. Return type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Cílový modul runtime nepodporuje v přepisech kovariantní návratové typy. Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember"> <source>Target runtime doesn't support 'protected', 'protected internal', or 'private protected' accessibility for a member of an interface.</source> <target state="translated">Cílový modul runtime nepodporuje pro člena rozhraní přístupnost na úrovni Protected, Protected internal nebo Private protected.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces"> <source>Target runtime doesn't support static abstract members in interfaces.</source> <target state="new">Target runtime doesn't support static abstract members in interfaces.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support static abstract members in interfaces.</source> <target state="new">'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support static abstract members in interfaces.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv"> <source>The target runtime doesn't support extensible or runtime-environment default calling conventions.</source> <target state="translated">Cílový modul runtime nepodporuje rozšiřitelné konvence volání ani konvence volání výchozí pro prostředí modulu runtime.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedAPIInRecord"> <source>'{0}' cannot be sealed because containing record is not sealed.</source> <target state="translated">Typ {0} nemůže být zapečetěný, protože není zapečetěný obsahující záznam.</target> <note /> </trans-unit> <trans-unit id="ERR_SignatureMismatchInRecord"> <source>Record member '{0}' must return '{1}'.</source> <target state="translated">Člen záznamu {0} musí vracet {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramDisallowsMainType"> <source>Cannot specify /main if there is a compilation unit with top-level statements.</source> <target state="translated">Pokud existuje jednotka kompilace s příkazy nejvyšší úrovně, nedá se zadat /main.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramIsEmpty"> <source>At least one top-level statement must be non-empty.</source> <target state="new">At least one top-level statement must be non-empty.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement"> <source>Cannot use local variable or local function '{0}' declared in a top-level statement in this context.</source> <target state="translated">Místní proměnná nebo místní funkce {0} deklarovaná v příkazu nejvyšší úrovně v tomto kontextu se nedá použít.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramMultipleUnitsWithTopLevelStatements"> <source>Only one compilation unit can have top-level statements.</source> <target state="translated">Příkazy nejvyšší úrovně může mít jen jedna jednotka kompilace.</target> <note /> </trans-unit> <trans-unit id="ERR_SimpleProgramNotAnExecutable"> <source>Program using top-level statements must be an executable.</source> <target state="translated">Program, který používá příkazy nejvyšší úrovně, musí být spustitelný.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleElementPositionalPatternRequiresDisambiguation"> <source>A single-element deconstruct pattern requires some other syntax for disambiguation. It is recommended to add a discard designator '_' after the close paren ')'.</source> <target state="translated">Vzor deconstruct s jedním elementem vyžaduje určitou další syntaxi pro zajištění jednoznačnosti. Doporučuje se přidat označení discard „_“ za koncovou závorku „)“.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAPIInRecord"> <source>Record member '{0}' may not be static.</source> <target state="translated">Člen záznamu {0} nemůže být statický.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAnonymousFunctionCannotCaptureThis"> <source>A static anonymous function cannot contain a reference to 'this' or 'base'.</source> <target state="translated">Statická anonymní funkce nemůže obsahovat odkaz na this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticAnonymousFunctionCannotCaptureVariable"> <source>A static anonymous function cannot contain a reference to '{0}'.</source> <target state="translated">Statická anonymní funkce nemůže obsahovat odkaz na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticLocalFunctionCannotCaptureThis"> <source>A static local function cannot contain a reference to 'this' or 'base'.</source> <target state="translated">Statická lokální funkce nesmí obsahovat odkaz na this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticLocalFunctionCannotCaptureVariable"> <source>A static local function cannot contain a reference to '{0}'.</source> <target state="translated">Statická lokální funkce nesmí obsahovat odkaz na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticMemberCantBeReadOnly"> <source>Static member '{0}' cannot be marked 'readonly'.</source> <target state="translated">Statický člen {0} se nedá označit modifikátorem readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_StdInOptionProvidedButConsoleInputIsNotRedirected"> <source>stdin argument '-' is specified, but input has not been redirected from the standard input stream.</source> <target state="translated">Zadal se argument stdin -, ale vstup se nepřesměroval na stream standardního vstupu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchArmSubsumed"> <source>The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.</source> <target state="translated">Vzor není dostupný. Už se zpracoval v jiné části výrazu switch nebo není možné pro něj najít shodu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchCaseSubsumed"> <source>The switch case is unreachable. It has already been handled by a previous case or it is impossible to match.</source> <target state="translated">Případ příkazu switch není dostupný. Už se zpracoval v jiném případu nebo není možné pro něj najít shodu.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchExpressionNoBestType"> <source>No best type was found for the switch expression.</source> <target state="translated">Pro výraz switch se nenašel žádný optimální typ.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchGoverningExpressionRequiresParens"> <source>Parentheses are required around the switch governing expression.</source> <target state="translated">Řídící výraz switch je nutné uzavřít do závorek.</target> <note /> </trans-unit> <trans-unit id="ERR_TopLevelStatementAfterNamespaceOrType"> <source>Top-level statements must precede namespace and type declarations.</source> <target state="translated">Příkazy nejvyšší úrovně se musí nacházet před obory názvů a deklaracemi typů.</target> <note /> </trans-unit> <trans-unit id="ERR_TripleDotNotAllowed"> <source>Unexpected character sequence '...'</source> <target state="translated">Neočekáváná posloupnost znaků ...</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNameMismatch"> <source>The name '{0}' does not identify tuple element '{1}'.</source> <target state="translated">Název {0} neidentifikuje element tuple {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleSizesMismatchForBinOps"> <source>Tuple types used as operands of an == or != operator must have matching cardinalities. But this operator has tuple types of cardinality {0} on the left and {1} on the right.</source> <target state="translated">Typy řazené kolekce členů, které se používají jako operandy operátoru == nebo !=, musí mít odpovídající kardinality. U tohoto operátoru je ale kardinalita typů řazené kolekce členů vlevo {0} a vpravo {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeConstraintsMustBeUniqueAndFirst"> <source>The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list.</source> <target state="translated">Omezení class, struct, unmanaged, notnull a default se nedají kombinovat ani použít více než jednou a v seznamu omezení se musí zadat jako první.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeIsNotAnInterpolatedStringHandlerType"> <source>'{0}' is not an interpolated string handler type.</source> <target state="new">'{0}' is not an interpolated string handler type.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeMustBePublic"> <source>Type '{0}' must be public to be used as a calling convention.</source> <target state="translated">Aby se typ {0} dal použít jako konvence volání, musí být veřejný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly"> <source>'{0}' is attributed with 'UnmanagedCallersOnly' and cannot be called directly. Obtain a function pointer to this method.</source> <target state="translated">{0} má atribut UnmanagedCallersOnly a nedá se volat napřímo. Pro tuto metodu získejte ukazatel na funkci.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate"> <source>'{0}' is attributed with 'UnmanagedCallersOnly' and cannot be converted to a delegate type. Obtain a function pointer to this method.</source> <target state="translated">{0} má atribut UnmanagedCallersOnly a nedá se převést na typ delegáta. Pro tuto metodu získejte ukazatel na funkci.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_WrongArityAsyncReturn"> <source>A generic task-like return type was expected, but the type '{0}' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic.</source> <target state="new">A generic task-like return type was expected, but the type '{0}' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic.</target> <note /> </trans-unit> <trans-unit id="HDN_DuplicateWithGlobalUsing"> <source>The using directive for '{0}' appeared previously as global using</source> <target state="new">The using directive for '{0}' appeared previously as global using</target> <note /> </trans-unit> <trans-unit id="HDN_DuplicateWithGlobalUsing_Title"> <source>The using directive appeared previously as global using</source> <target state="new">The using directive appeared previously as global using</target> <note /> </trans-unit> <trans-unit id="IDS_AsyncMethodBuilderOverride"> <source>async method builder override</source> <target state="new">async method builder override</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCovariantReturnsForOverrides"> <source>covariant returns</source> <target state="translated">kovariantní návratové hodnoty</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDiscards"> <source>discards</source> <target state="translated">discards</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtendedPropertyPatterns"> <source>extended property patterns</source> <target state="new">extended property patterns</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFileScopedNamespace"> <source>file-scoped namespace</source> <target state="new">file-scoped namespace</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGenericAttributes"> <source>generic attributes</source> <target state="new">generic attributes</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGlobalUsing"> <source>global using directive</source> <target state="new">global using directive</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitObjectCreation"> <source>target-typed object creation</source> <target state="translated">Vytvoření objektu s cílovým typem</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImprovedInterpolatedStrings"> <source>interpolated string handlers</source> <target state="new">interpolated string handlers</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInferredDelegateType"> <source>inferred delegate type</source> <target state="new">inferred delegate type</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaAttributes"> <source>lambda attributes</source> <target state="new">lambda attributes</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaReturnType"> <source>lambda return type</source> <target state="new">lambda return type</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLineSpanDirective"> <source>line span directive</source> <target state="new">line span directive</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureParameterlessStructConstructors"> <source>parameterless struct constructors</source> <target state="new">parameterless struct constructors</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePositionalFieldsInRecords"> <source>positional fields in records</source> <target state="new">positional fields in records</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecordStructs"> <source>record structs</source> <target state="new">record structs</target> <note>'record structs' is not localizable.</note> </trans-unit> <trans-unit id="IDS_FeatureSealedToStringInRecord"> <source>sealed ToString in record</source> <target state="translated">zapečetěný ToString v záznamu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStructFieldInitializers"> <source>struct field initializers</source> <target state="new">struct field initializers</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureWithOnAnonymousTypes"> <source>with on anonymous types</source> <target state="new">with on anonymous types</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticAbstractMembersInInterfaces"> <source>static abstract members in interfaces</source> <target state="new">static abstract members in interfaces</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureWithOnStructs"> <source>with on structs</source> <target state="new">with on structs</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework"> <source>The assembly '{0}' containing type '{1}' references .NET Framework, which is not supported.</source> <target state="translated">Sestavení {0}, které obsahuje typ {1}, se odkazuje na architekturu .NET Framework, což se nepodporuje.</target> <note>{1} is the type that was loaded, {0} is the containing assembly.</note> </trans-unit> <trans-unit id="WRN_AnalyzerReferencesFramework_Title"> <source>The loaded assembly references .NET Framework, which is not supported.</source> <target state="translated">Načtené sestavení se odkazuje na architekturu .NET Framework, což se nepodporuje</target> <note /> </trans-unit> <trans-unit id="WRN_AttrDependentTypeNotAllowed"> <source>Type '{0}' cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type '{0}' cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="WRN_AttrDependentTypeNotAllowed_Title"> <source>Type cannot be used in this context because it cannot be represented in metadata.</source> <target state="new">Type cannot be used in this context because it cannot be represented in metadata.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeHasInvalidParameterName_Title"> <source>The CallerArgumentExpressionAttribute is applied with an invalid parameter name.</source> <target state="new">The CallerArgumentExpressionAttribute is applied with an invalid parameter name.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it's self-referential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionAttributeSelfReferential_Title"> <source>The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-refential.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter will have no effect because it's self-refential.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionParamForUnconsumedLocation"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</target> <note /> </trans-unit> <trans-unit id="WRN_CallerArgumentExpressionParamForUnconsumedLocation_Title"> <source>The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerFilePathAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNamePreferredOverCallerArgumentExpression"> <source>The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute.</source> <target state="new">The CallerArgumentExpressionAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerMemberNameAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNamePreferredOverCallerArgumentExpression_Title"> <source>The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute</source> <target state="new">The CallerArgumentExpressionAttribute will have no effect; it is overridden by the CallerMemberNameAttribute</target> <note /> </trans-unit> <trans-unit id="WRN_CompileTimeCheckedOverflow"> <source>The operation may overflow '{0}' at runtime (use 'unchecked' syntax to override)</source> <target state="new">The operation may overflow '{0}' at runtime (use 'unchecked' syntax to override)</target> <note /> </trans-unit> <trans-unit id="WRN_CompileTimeCheckedOverflow_Title"> <source>The operation may overflow at runtime (use 'unchecked' syntax to override)</source> <target state="new">The operation may overflow at runtime (use 'unchecked' syntax to override)</target> <note /> </trans-unit> <trans-unit id="WRN_DoNotCompareFunctionPointers"> <source>Comparison of function pointers might yield an unexpected result, since pointers to the same function may be distinct.</source> <target state="translated">Porovnání ukazatelů funkcí může přinést neočekávaný výsledek, protože ukazatele na stejnou funkci můžou být rozdílné.</target> <note /> </trans-unit> <trans-unit id="WRN_DoNotCompareFunctionPointers_Title"> <source>Do not compare function pointer values</source> <target state="translated">Neporovnávat hodnoty ukazatelů funkcí</target> <note /> </trans-unit> <trans-unit id="WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters"> <source>InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</source> <target state="new">InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</target> <note /> </trans-unit> <trans-unit id="WRN_InterpolatedStringHandlerArgumentAttributeIgnoredOnLambdaParameters_Title"> <source>InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</source> <target state="new">InterpolatedStringHandlerArgument has no effect when applied to lambda parameters and will be ignored at the call site.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterNotNullIfNotNull"> <source>Parameter '{0}' must have a non-null value when exiting because parameter '{1}' is non-null.</source> <target state="translated">Parametr {0} musí mít při ukončení hodnotu jinou než null, protože parametr {1} není null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterNotNullIfNotNull_Title"> <source>Parameter must have a non-null value when exiting because parameter referenced by NotNullIfNotNull is non-null.</source> <target state="translated">Parametr musí mít při ukončení hodnotu jinou než null, protože parametr, na který se odkazuje NotNullIfNotNull není null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterOccursAfterInterpolatedStringHandlerParameter"> <source>Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.</source> <target state="new">Parameter {0} occurs after {1} in the parameter list, but is used as an argument for interpolated string handler conversions. This will require the caller to reorder parameters with named arguments at the call site. Consider putting the interpolated string handler parameter after all arguments involved.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterOccursAfterInterpolatedStringHandlerParameter_Title"> <source>Parameter to interpolated string handler conversion occurs after handler parameter</source> <target state="new">Parameter to interpolated string handler conversion occurs after handler parameter</target> <note /> </trans-unit> <trans-unit id="WRN_RecordEqualsWithoutGetHashCode"> <source>'{0}' defines 'Equals' but not 'GetHashCode'</source> <target state="translated">{0} definuje Equals, ale ne GetHashCode.</target> <note>'GetHashCode' and 'Equals' are not localizable.</note> </trans-unit> <trans-unit id="WRN_RecordEqualsWithoutGetHashCode_Title"> <source>Record defines 'Equals' but not 'GetHashCode'.</source> <target state="translated">Záznam definuje Equals, ale ne GetHashCode</target> <note>'GetHashCode' and 'Equals' are not localizable.</note> </trans-unit> <trans-unit id="IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction"> <source>Mixed declarations and expressions in deconstruction</source> <target state="translated">Smíšené deklarace a výrazy v dekonstrukci</target> <note /> </trans-unit> <trans-unit id="WRN_PartialMethodTypeDifference"> <source>Partial method declarations '{0}' and '{1}' have signature differences.</source> <target state="new">Partial method declarations '{0}' and '{1}' have signature differences.</target> <note /> </trans-unit> <trans-unit id="WRN_PartialMethodTypeDifference_Title"> <source>Partial method declarations have signature differences.</source> <target state="new">Partial method declarations have signature differences.</target> <note /> </trans-unit> <trans-unit id="WRN_RecordNamedDisallowed"> <source>Types and aliases should not be named 'record'.</source> <target state="translated">Typy a aliasy by neměly mít název record.</target> <note /> </trans-unit> <trans-unit id="WRN_RecordNamedDisallowed_Title"> <source>Types and aliases should not be named 'record'.</source> <target state="translated">Typy a aliasy by neměly mít název record</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnNotNullIfNotNull"> <source>Return value must be non-null because parameter '{0}' is non-null.</source> <target state="translated">Návratová hodnota musí být jiná než null, protože parametr {0} není null.</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnNotNullIfNotNull_Title"> <source>Return value must be non-null because parameter is non-null.</source> <target state="translated">Návratová hodnota musí být jiná než null, protože parametr není null</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue"> <source>The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value. For example, the pattern '{0}' is not covered.</source> <target state="translated">Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu. Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue_Title"> <source>The switch expression does not handle some values of its input type (it is not exhaustive) involving an unnamed enum value.</source> <target state="translated">Výraz switch nezachycuje některé hodnoty vstupního typu (není úplný) včetně nepojmenované hodnoty výčtu.</target> <note /> </trans-unit> <trans-unit id="WRN_SyncAndAsyncEntryPoints"> <source>Method '{0}' will not be used as an entry point because a synchronous entry point '{1}' was found.</source> <target state="translated">Metoda {0} se nepoužije jako vstupní bod, protože se našel synchronní vstupní bod {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeNotFound"> <source>Type '{0}' is not defined.</source> <target state="translated">Typ {0} není definovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedArgumentList"> <source>Unexpected argument list.</source> <target state="translated">Neočekávaný seznam argumentů</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedOrMissingConstructorInitializerInRecord"> <source>A constructor declared in a record with parameter list must have 'this' constructor initializer.</source> <target state="translated">Konstruktor deklarovaný v záznamu se seznamem parametrů musí mít inicializátor konstruktoru this.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedVarianceStaticMember"> <source>Invalid variance: The type parameter '{1}' must be {3} valid on '{0}' unless language version '{4}' or greater is used. '{1}' is {2}.</source> <target state="translated">Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}, pokud není použita verze jazyka {4} nebo vyšší. {1} je {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedBoundWithClass"> <source>'{0}': cannot specify both a constraint class and the 'unmanaged' constraint</source> <target state="translated">{0}: Nejde zadat třídu omezení a zároveň omezení unmanaged.</target> <note /> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric"> <source>Methods attributed with 'UnmanagedCallersOnly' cannot have generic type parameters and cannot be declared in a generic type.</source> <target state="translated">Metody, které mají atribut UnmanagedCallersOnly, nemůžou mít obecné typy parametrů a nedají se deklarovat v obecném typu.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedCallersOnlyRequiresStatic"> <source>'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.</source> <target state="needs-review-translation">UnmanagedCallersOnly se dá použít jen pro běžné statické metody nebo statické místní funkce.</target> <note>UnmanagedCallersOnly is not localizable.</note> </trans-unit> <trans-unit id="ERR_UnmanagedConstraintNotSatisfied"> <source>The type '{2}' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ, který nemůže mít hodnotu null, ani nesmí v žádné úrovni vnoření obsahovat pole, které by ji povolovalo, aby se dal použít jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedCallingConvention"> <source>The calling convention of '{0}' is not supported by the language.</source> <target state="translated">Jazyk nepodporuje konvenci volání {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedTypeForRelationalPattern"> <source>Relational patterns may not be used for a value of type '{0}'.</source> <target state="translated">Relační vzory se nedají používat pro hodnotu typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UsingVarInSwitchCase"> <source>A using variable cannot be used directly within a switch section (consider using braces). </source> <target state="translated">Proměnnou using není možné v sekci switch použít přímo (zvažte použití složených závorek). </target> <note /> </trans-unit> <trans-unit id="ERR_VarMayNotBindToType"> <source>The syntax 'var' for a pattern is not permitted to refer to a type, but '{0}' is in scope here.</source> <target state="translated">U syntaxe var pro vzor se nepovoluje odkazování na typ, ale {0} je tady v rámci rozsahu.</target> <note /> </trans-unit> <trans-unit id="ERR_VarianceInterfaceNesting"> <source>Enums, classes, and structures cannot be declared in an interface that has an 'in' or 'out' type parameter.</source> <target state="translated">Výčty, třídy a struktury není možné deklarovat v rozhraní, které má parametr typu in/out.</target> <note /> </trans-unit> <trans-unit id="ERR_WrongFuncPtrCallingConvention"> <source>Calling convention of '{0}' is not compatible with '{1}'.</source> <target state="translated">Konvence volání pro {0} není kompatibilní s {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_WrongNumberOfSubpatterns"> <source>Matching the tuple type '{0}' requires '{1}' subpatterns, but '{2}' subpatterns are present.</source> <target state="translated">Přiřazení k řazené kolekci členů typu {0} vyžaduje dílčí vzory {1}, ale k dispozici jsou dílčí vzory {2}.</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidInputFileName"> <source>File name '{0}' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long</source> <target state="translated">Název souboru {0} je prázdný, obsahuje neplatné znaky, má specifikaci jednotky bez absolutní cesty nebo je moc dlouhý.</target> <note /> </trans-unit> <trans-unit id="IDS_AddressOfMethodGroup"> <source>&amp;method group</source> <target state="translated">skupina &amp;metod</target> <note /> </trans-unit> <trans-unit id="IDS_CSCHelp"> <source> Visual C# Compiler Options - OUTPUT FILES - -out:&lt;file&gt; Specify output file name (default: base name of file with main class or first file) -target:exe Build a console executable (default) (Short form: -t:exe) -target:winexe Build a Windows executable (Short form: -t:winexe) -target:library Build a library (Short form: -t:library) -target:module Build a module that can be added to another assembly (Short form: -t:module) -target:appcontainerexe Build an Appcontainer executable (Short form: -t:appcontainerexe) -target:winmdobj Build a Windows Runtime intermediate file that is consumed by WinMDExp (Short form: -t:winmdobj) -doc:&lt;file&gt; XML Documentation file to generate -refout:&lt;file&gt; Reference assembly output to generate -platform:&lt;string&gt; Limit which platforms this code can run on: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred, or anycpu. The default is anycpu. - INPUT FILES - -recurse:&lt;wildcard&gt; Include all files in the current directory and subdirectories according to the wildcard specifications -reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: -r) -reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: -r) -addmodule:&lt;file list&gt; Link the specified modules into this assembly -link:&lt;file list&gt; Embed metadata from the specified interop assembly files (Short form: -l) -analyzer:&lt;file list&gt; Run the analyzers from this assembly (Short form: -a) -additionalfile:&lt;file list&gt; Additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings. -embed Embed all source files in the PDB. -embed:&lt;file list&gt; Embed specific files in the PDB. - RESOURCES - -win32res:&lt;file&gt; Specify a Win32 resource file (.res) -win32icon:&lt;file&gt; Use this icon for the output -win32manifest:&lt;file&gt; Specify a Win32 manifest file (.xml) -nowin32manifest Do not include the default Win32 manifest -resource:&lt;resinfo&gt; Embed the specified resource (Short form: -res) -linkresource:&lt;resinfo&gt; Link the specified resource to this assembly (Short form: -linkres) Where the resinfo format is &lt;file&gt;[,&lt;string name&gt;[,public|private]] - CODE GENERATION - -debug[+|-] Emit debugging information -debug:{full|pdbonly|portable|embedded} Specify debugging type ('full' is default, 'portable' is a cross-platform format, 'embedded' is a cross-platform format embedded into the target .dll or .exe) -optimize[+|-] Enable optimizations (Short form: -o) -deterministic Produce a deterministic assembly (including module version GUID and timestamp) -refonly Produce a reference assembly in place of the main output -instrument:TestCoverage Produce an assembly instrumented to collect coverage information -sourcelink:&lt;file&gt; Source link info to embed into PDB. - ERRORS AND WARNINGS - -warnaserror[+|-] Report all warnings as errors -warnaserror[+|-]:&lt;warn list&gt; Report specific warnings as errors (use "nullable" for all nullability warnings) -warn:&lt;n&gt; Set warning level (0 or higher) (Short form: -w) -nowarn:&lt;warn list&gt; Disable specific warning messages (use "nullable" for all nullability warnings) -ruleset:&lt;file&gt; Specify a ruleset file that disables specific diagnostics. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Specify a file to log all compiler and analyzer diagnostics. sarif_version:{1|2|2.1} Default is 1. 2 and 2.1 both mean SARIF version 2.1.0. -reportanalyzer Report additional analyzer information, such as execution time. -skipanalyzers[+|-] Skip execution of diagnostic analyzers. - LANGUAGE - -checked[+|-] Generate overflow checks -unsafe[+|-] Allow 'unsafe' code -define:&lt;symbol list&gt; Define conditional compilation symbol(s) (Short form: -d) -langversion:? Display the allowed values for language version -langversion:&lt;string&gt; Specify language version such as `latest` (latest version, including minor versions), `default` (same as `latest`), `latestmajor` (latest version, excluding minor versions), `preview` (latest version, including features in unsupported preview), or specific versions like `6` or `7.1` -nullable[+|-] Specify nullable context option enable|disable. -nullable:{enable|disable|warnings|annotations} Specify nullable context option enable|disable|warnings|annotations. - SECURITY - -delaysign[+|-] Delay-sign the assembly using only the public portion of the strong name key -publicsign[+|-] Public-sign the assembly using only the public portion of the strong name key -keyfile:&lt;file&gt; Specify a strong name key file -keycontainer:&lt;string&gt; Specify a strong name key container -highentropyva[+|-] Enable high-entropy ASLR - MISCELLANEOUS - @&lt;file&gt; Read response file for more options -help Display this usage message (Short form: -?) -nologo Suppress compiler copyright message -noconfig Do not auto include CSC.RSP file -parallel[+|-] Concurrent build. -version Display the compiler version number and exit. - ADVANCED - -baseaddress:&lt;address&gt; Base address for the library to be built -checksumalgorithm:&lt;alg&gt; Specify algorithm for calculating source file checksum stored in PDB. Supported values are: SHA1 or SHA256 (default). -codepage:&lt;n&gt; Specify the codepage to use when opening source files -utf8output Output compiler messages in UTF-8 encoding -main:&lt;type&gt; Specify the type that contains the entry point (ignore all other possible entry points) (Short form: -m) -fullpaths Compiler generates fully qualified paths -filealign:&lt;n&gt; Specify the alignment used for output file sections -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Specify a mapping for source path names output by the compiler. -pdb:&lt;file&gt; Specify debug information file name (default: output file name with .pdb extension) -errorendlocation Output line and column of the end location of each error -preferreduilang Specify the preferred output language name. -nosdkpath Disable searching the default SDK path for standard library assemblies. -nostdlib[+|-] Do not reference standard library (mscorlib.dll) -subsystemversion:&lt;string&gt; Specify subsystem version of this assembly -lib:&lt;file list&gt; Specify additional directories to search in for references -errorreport:&lt;string&gt; Specify how to handle internal compiler errors: prompt, send, queue, or none. The default is queue. -appconfig:&lt;file&gt; Specify an application configuration file containing assembly binding settings -moduleassemblyname:&lt;string&gt; Name of the assembly which this module will be a part of -modulename:&lt;string&gt; Specify the name of the source module -generatedfilesout:&lt;dir&gt; Place files generated during compilation in the specified directory. </source> <target state="translated"> Parametry kompilátoru Visual C# - VÝSTUPNÍ SOUBORY - -out:&lt;file&gt; Určuje název výstupního souboru (výchozí: základní název souboru s hlavní třídou nebo prvního souboru) -target:exe Vytvoří spustitelný soubor konzoly (výchozí). (Krátký formát: -t:exe) -target:winexe Vytvoří spustitelný soubor systému Windows. (Krátký formát: -t:winexe) -target:library Vytvoří knihovnu. (Krátký formát: -t:library) -target:module Vytvoří modul, který se dá přidat do jiného sestavení. (Krátký formát: -t:module) -target:appcontainerexe Sestaví spustitelný soubor kontejneru Appcontainer. (Krátký formát: -t:appcontainerexe) -target:winmdobj Sestaví pomocný soubor modulu Windows Runtime, který využívá knihovna WinMDExp. (Krátký formát: -t:winmdobj) -doc:&lt;file&gt; Soubor dokumentace XML, který má být vygenerován -refout:&lt;file&gt; Výstup referenčního sestavení, který má být vygenerován -platform:&lt;string&gt; Omezuje platformy, na kterých lze tento kód spustit: x86, Itanium, x64, arm, arm64, anycpu32bitpreferred nebo anycpu. Výchozí nastavení je anycpu. - VSTUPNÍ SOUBORY - -recurse:&lt;wildcard&gt; Zahrne všechny soubory v aktuálním adresáři a jeho podadresářích podle zadaného zástupného znaku. -reference:&lt;alias&gt;=&lt;file&gt; Odkazuje na metadata ze zadaného souboru sestavení pomocí daného aliasu. (Krátký formát: -r) -reference:&lt;file list&gt; Odkazuje na metadata ze zadaných souborů sestavení (Krátký formát: -r) -addmodule:&lt;file list&gt; Připojí zadané moduly k tomuto sestavení. -link:&lt;file list&gt; Vloží metadata ze zadaných souborů sestavení spolupráce (Krátký formát: -l) -analyzer:&lt;file list&gt; Spustí analyzátory z tohoto sestavení. (Krátký formát: -a) -additionalfile:&lt;file list&gt; Další soubory, které přímo neovlivňují generování kódu, ale analyzátory můžou jejich pomocí produkovat chyby nebo upozornění. -embed Vloží všechny zdrojové soubory do PDB. -embed:&lt;file list&gt; Vloží konkrétní soubory do PDB. - PROSTŘEDKY - -win32res:&lt;file&gt; Určuje soubor prostředků Win32 (.res). -win32icon:&lt;file&gt; Použije pro výstup zadanou ikonu. -win32manifest:&lt;file&gt; Určuje soubor manifestu Win32 (.xml). -nowin32manifest Nezahrne výchozí manifest Win32. -resource:&lt;resinfo&gt; Vloží zadaný prostředek. (Krátký formát: -res) -linkresource:&lt;resinfo&gt; Propojí zadaný prostředek s tímto sestavením. (Krátký formát: -linkres) Prostředek má formát is &lt;file&gt;[,&lt;string name&gt;[,public|private]]. - GENEROVÁNÍ KÓDU - -debug[+|-] Generuje ladicí informace. -debug:{full|pdbonly|portable|embedded} Určuje typ ladění (výchozí je možnost full, portable je formát napříč platformami, embedded je formát napříč platformami vložený do cílového souboru .dll nebo .exe). -optimize[+|-] Povolí optimalizace. (Krátký formát: -o) -deterministic Vytvoří deterministické sestavení (včetně GUID verze modulu a časového razítka). -refonly Vytvoří referenční sestavení na místě hlavního výstupu. -instrument:TestCoverage Vytvoří sestavení instrumentované ke shromažďování informací o pokrytí. -sourcelink:&lt;file&gt; Informace o zdrojovém odkazu vkládané do souboru PDB.. - CHYBY A UPOZORNĚNÍ - -warnaserror[+|-] Hlásí všechna upozornění jako chyby. -warnaserror[+|-]:&lt;warn list&gt; Hlásí zadaná upozornění jako chyby. (Pro všechna upozornění na možnost použití hodnoty null použijte nullable.) -warn:&lt;n&gt; Nastaví úroveň pro upozornění (0 a více). (Krátký formát: -w) -nowarn:&lt;warn list&gt; Zakáže zadaná upozornění. (Pro všechna upozornění na možnost použití hodnoty null použijte nullable.) -ruleset:&lt;file&gt; Určuje soubor sady pravidel, která zakazuje specifickou diagnostiku. -errorlog:&lt;file&gt;[,version=&lt;sarif_version&gt;] Určuje soubor pro protokolování veškeré diagnostiky kompilátoru a analyzátoru. verze_sarif:{1|2|2.1} Výchozí jsou 1. 2 a 2.1. Obojí znamená SARIF verze 2.1.0. -reportanalyzer Hlásí další informace analyzátoru, např. dobu spuštění. -skipanalyzers[+|-] Přeskočí spouštění diagnostických analyzátorů. - JAZYK - -checked[+|-] Generuje kontroly přetečení. -unsafe[+|-] Povoluje nezabezpečený kód. -define:&lt;symbol list&gt; Definuje symboly podmíněné kompilace. (Krátký formát: -d) -langversion:? Zobrazuje povolené hodnoty pro verzi jazyka. -langversion:&lt;string&gt; Určuje verzi jazyka, například: latest (poslední verze včetně podverzí), default (stejné jako latest), latestmajor (poslední verze bez podverzí), preview (poslední verze včetně funkcí v nepodporované verzi preview) nebo konkrétní verze, například 6 nebo 7.1. -nullable[+|-] Určuje pro kontext s hodnotou null možnosti enable|disable. -nullable:{enable|disable|warnings|annotations} Určuje pro kontext s hodnotou null možnosti enable|disable|warnings|annotations. - ZABEZPEČENÍ - -delaysign[+|-] Vytvoří zpožděný podpis sestavení s využitím jenom veřejné části klíče silného názvu. -publicsign[+|-] Vytvoří veřejný podpis sestavení s využitím jenom veřejné části klíče silného názvu. -keyfile:&lt;file&gt; Určuje soubor klíče se silným názvem. -keycontainer:&lt;string&gt; Určuje kontejner klíče se silným názvem. -highentropyva[+|-] Povolí ASLR s vysokou entropií. - RŮZNÉ - @&lt;file&gt; Načte další možnosti ze souboru odpovědí. -help Zobrazí tuto zprávu o použití. (Krátký formát: -?) -nologo Potlačí zprávu o autorských právech kompilátoru. -noconfig Nezahrnuje automaticky soubor CSC.RSP. -parallel[+|-] Souběžné sestavení. -version Zobrazí číslo verze kompilátoru a ukončí se. - POKROČILÉ - -baseaddress:&lt;address&gt; Základní adresa pro knihovnu, která se má sestavit. -checksumalgorithm:&lt;alg&gt; Určuje algoritmus pro výpočet kontrolního součtu zdrojového souboru uloženého v PDB. Podporované hodnoty: SHA1 nebo SHA256 (výchozí). -codepage:&lt;n&gt; Určuje znakovou stránku, která se má použít při otevírání zdrojových souborů. -utf8output Určuje výstup zpráv kompilátoru v kódování UTF-8. -main:&lt;typ&gt; Určuje typ obsahující vstupní bod (ignoruje všechny ostatní potenciální vstupní body). (Krátký formát: -m) -fullpaths Kompilátor generuje úplné cesty. -filealign:&lt;n&gt; Určuje zarovnání použité pro oddíly výstupního souboru. -pathmap:&lt;K1&gt;=&lt;V1&gt;,&lt;K2&gt;=&lt;V2&gt;,... Určuje mapování pro výstup zdrojových názvů cest kompilátorem. -pdb:&lt;file&gt; Určuje název souboru ladicích informací (výchozí: název výstupního souboru s příponou .pdb). -errorendlocation Vypíše řádek a sloupec koncového umístění jednotlivých chyb. -preferreduilang Určuje název upřednostňovaného výstupního jazyka. -nosdkpath Zakazuje hledání cesty k výchozí sadě SDK pro sestavení standardních knihoven. -nostdlib[+|-] Neodkazuje na standardní knihovnu (mscorlib.dll). -subsystemversion:&lt;string&gt; Určuje verzi subsystému tohoto sestavení. -lib:&lt;file list&gt; Určuje další adresáře, ve kterých se mají hledat reference. -errorreport:&lt;řetězec&gt; Určuje způsob zpracování interních chyb kompilátoru: prompt, send, queue nebo none. Výchozí možnost je queue (zařadit do fronty). -appconfig:&lt;file&gt; Určuje konfigurační soubor aplikace, který obsahuje nastavení vazby sestavení. -moduleassemblyname:&lt;string&gt; Určuje název sestavení, jehož součástí bude tento modul. -modulename:&lt;string&gt; Určuje název zdrojového modulu. -generatedfilesout:&lt;dir&gt; Umístí soubory vygenerované během kompilace do zadaného adresáře. </target> <note>Visual C# Compiler Options</note> </trans-unit> <trans-unit id="IDS_DefaultInterfaceImplementation"> <source>default interface implementation</source> <target state="translated">implementace výchozího rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_Disposable"> <source>disposable</source> <target state="translated">jednoúčelové</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAltInterpolatedVerbatimStrings"> <source>alternative interpolated verbatim strings</source> <target state="translated">alternativní interpolované doslovné řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAndPattern"> <source>and pattern</source> <target state="translated">vzor and</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncUsing"> <source>asynchronous using</source> <target state="translated">asynchronní příkaz using</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCoalesceAssignmentExpression"> <source>coalescing assignment</source> <target state="translated">slučovací přiřazení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureConstantInterpolatedStrings"> <source>constant interpolated strings</source> <target state="translated">konstantní interpolované řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefaultTypeParameterConstraint"> <source>default type parameter constraints</source> <target state="translated">výchozí omezení parametru typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDelegateGenericTypeConstraint"> <source>delegate generic type constraints</source> <target state="translated">delegovat obecná omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureEnumGenericTypeConstraint"> <source>enum generic type constraints</source> <target state="translated">výčet obecných omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionVariablesInQueriesAndInitializers"> <source>declaration of expression variables in member initializers and queries</source> <target state="translated">deklarace proměnných výrazu v inicializátorech členů a dotazech</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtendedPartialMethods"> <source>extended partial methods</source> <target state="translated">rozšířené částečné metody</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensibleFixedStatement"> <source>extensible fixed statement</source> <target state="translated">rozšiřitelný příkaz fixed</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionGetAsyncEnumerator"> <source>extension GetAsyncEnumerator</source> <target state="translated">rozšíření GetAsyncEnumerator</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionGetEnumerator"> <source>extension GetEnumerator</source> <target state="translated">rozšíření GetEnumerator</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExternLocalFunctions"> <source>extern local functions</source> <target state="translated">externí místní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFunctionPointers"> <source>function pointers</source> <target state="translated">ukazatele na funkci</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIndexOperator"> <source>index operator</source> <target state="translated">operátor indexu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIndexingMovableFixedBuffers"> <source>indexing movable fixed buffers</source> <target state="translated">indexování mobilních vyrovnávacích pamětí pevné velikosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInitOnlySetters"> <source>init-only setters</source> <target state="translated">metody setter jenom pro inicializaci</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLocalFunctionAttributes"> <source>local function attributes</source> <target state="translated">atributy místních funkcí</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambdaDiscardParameters"> <source>lambda discard parameters</source> <target state="translated">lambda – zahodit parametry</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureMemberNotNull"> <source>MemberNotNull attribute</source> <target state="translated">Atribut MemberNotNull</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureModuleInitializers"> <source>module initializers</source> <target state="translated">inicializátory modulů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNameShadowingInNestedFunctions"> <source>name shadowing in nested functions</source> <target state="translated">skrývání názvů ve vnořených funkcích</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNativeInt"> <source>native-sized integers</source> <target state="translated">Celá čísla s nativní velikostí</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNestedStackalloc"> <source>stackalloc in nested expressions</source> <target state="translated">stackalloc ve vnořených výrazech</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNotNullGenericTypeConstraint"> <source>notnull generic type constraint</source> <target state="translated">omezení obecného typu notnull</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNotPattern"> <source>not pattern</source> <target state="translated">vzor not</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullPointerConstantPattern"> <source>null pointer constant pattern</source> <target state="translated">konstantní vzor nulového ukazatele</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullableReferenceTypes"> <source>nullable reference types</source> <target state="translated">typy odkazů s možnou hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureObsoleteOnPropertyAccessor"> <source>obsolete on property accessor</source> <target state="translated">zastaralé u přístupového objektu vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOrPattern"> <source>or pattern</source> <target state="translated">vzor or</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureParenthesizedPattern"> <source>parenthesized pattern</source> <target state="translated">vzor se závorkami</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePragmaWarningEnable"> <source>warning action enable</source> <target state="translated">akce upozornění enable</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRangeOperator"> <source>range operator</source> <target state="translated">operátor rozsahu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyMembers"> <source>readonly members</source> <target state="translated">členové s modifikátorem readonly</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecords"> <source>records</source> <target state="translated">záznamy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRecursivePatterns"> <source>recursive patterns</source> <target state="translated">rekurzivní vzory</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefConditional"> <source>ref conditional expression</source> <target state="translated">referenční podmínka</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefFor"> <source>ref for-loop variables</source> <target state="translated">Proměnné smyčky for odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefForEach"> <source>ref foreach iteration variables</source> <target state="translated">Iterační proměnné foreach odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefReassignment"> <source>ref reassignment</source> <target state="translated">Opětovné přiřazení odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRelationalPattern"> <source>relational pattern</source> <target state="translated">relační vzor</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStackAllocInitializer"> <source>stackalloc initializer</source> <target state="translated">inicializátor výrazu stackalloc</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticAnonymousFunction"> <source>static anonymous function</source> <target state="translated">statická anonymní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticLocalFunctions"> <source>static local functions</source> <target state="translated">statické místní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureSwitchExpression"> <source>&lt;switch expression&gt;</source> <target state="translated">&lt;výraz přepínače&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTargetTypedConditional"> <source>target-typed conditional expression</source> <target state="translated">podmíněný výraz s typem cíle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTupleEquality"> <source>tuple equality</source> <target state="translated">rovnost řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTypePattern"> <source>type pattern</source> <target state="translated">vzor typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnconstrainedTypeParameterInNullCoalescingOperator"> <source>unconstrained type parameters in null coalescing operator</source> <target state="translated">parametry neomezeného typu v operátoru sloučení s hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnmanagedConstructedTypes"> <source>unmanaged constructed types</source> <target state="translated">nespravované konstruované typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUnmanagedGenericTypeConstraint"> <source>unmanaged generic type constraints</source> <target state="translated">nespravovaná obecná omezení typu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUsingDeclarations"> <source>using declarations</source> <target state="translated">deklarace using</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureVarianceSafetyForStaticInterfaceMembers"> <source>variance safety for static interface members</source> <target state="translated">zabezpečení odchylky pro statické členy rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_NULL"> <source>&lt;null&gt;</source> <target state="translated">&lt;null&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_OverrideWithConstraints"> <source>constraints for override and explicit interface implementation methods</source> <target state="translated">omezení pro metody přepsání a explicitní implementace rozhraní</target> <note /> </trans-unit> <trans-unit id="IDS_Parameter"> <source>parameter</source> <target state="translated">parametr</target> <note /> </trans-unit> <trans-unit id="IDS_Return"> <source>return</source> <target state="translated">návratový</target> <note /> </trans-unit> <trans-unit id="IDS_ThrowExpression"> <source>&lt;throw expression&gt;</source> <target state="translated">&lt;výraz throw&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_RELATEDERROR"> <source>(Location of symbol related to previous error)</source> <target state="translated">(Umístění symbolu vzhledem k předchozí chybě)</target> <note /> </trans-unit> <trans-unit id="IDS_RELATEDWARNING"> <source>(Location of symbol related to previous warning)</source> <target state="translated">(Umístění symbolu vzhledem k předchozímu upozornění)</target> <note /> </trans-unit> <trans-unit id="IDS_TopLevelStatements"> <source>top-level statements</source> <target state="translated">příkazy nejvyšší úrovně</target> <note /> </trans-unit> <trans-unit id="IDS_XMLIGNORED"> <source>&lt;!-- Badly formed XML comment ignored for member "{0}" --&gt;</source> <target state="translated">&lt;!-- Badly formed XML comment ignored for member "{0}" --&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_XMLIGNORED2"> <source> Badly formed XML file "{0}" cannot be included </source> <target state="translated"> Chybně vytvořený soubor XML {0} nejde zahrnout. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLFAILEDINCLUDE"> <source> Failed to insert some or all of included XML </source> <target state="translated"> Vložení části nebo veškerého zahrnutého kódu XML se nezdařilo. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLBADINCLUDE"> <source> Include tag is invalid </source> <target state="translated"> Značka Include je neplatná. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLNOINCLUDE"> <source> No matching elements were found for the following include tag </source> <target state="translated"> Pro následující značku include se nenašly žádné vyhovující prvky. </target> <note /> </trans-unit> <trans-unit id="IDS_XMLMISSINGINCLUDEFILE"> <source>Missing file attribute</source> <target state="translated">Atribut souboru se nenašel.</target> <note /> </trans-unit> <trans-unit id="IDS_XMLMISSINGINCLUDEPATH"> <source>Missing path attribute</source> <target state="translated">Atribut cesty se nenašel.</target> <note /> </trans-unit> <trans-unit id="IDS_GlobalNamespace"> <source>&lt;global namespace&gt;</source> <target state="translated">&lt;globální obor názvů&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGenerics"> <source>generics</source> <target state="translated">obecné</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAnonDelegates"> <source>anonymous methods</source> <target state="translated">anonymní metody</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureModuleAttrLoc"> <source>module as an attribute target specifier</source> <target state="translated">modul jako cílový specifikátor atributů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureGlobalNamespace"> <source>namespace alias qualifier</source> <target state="translated">kvalifikátor aliasu oboru názvů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureFixedBuffer"> <source>fixed size buffers</source> <target state="translated">vyrovnávací paměti pevné velikosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePragma"> <source>#pragma</source> <target state="translated">#pragma</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureStaticClasses"> <source>static classes</source> <target state="translated">statické třídy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyStructs"> <source>readonly structs</source> <target state="translated">struktury jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePartialTypes"> <source>partial types</source> <target state="translated">částečné typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsync"> <source>async function</source> <target state="translated">asynchronní funkce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureSwitchOnBool"> <source>switch on boolean type</source> <target state="translated">přepínač založený na typu boolean</target> <note /> </trans-unit> <trans-unit id="IDS_MethodGroup"> <source>method group</source> <target state="translated">skupina metod</target> <note /> </trans-unit> <trans-unit id="IDS_AnonMethod"> <source>anonymous method</source> <target state="translated">anonymní metoda</target> <note /> </trans-unit> <trans-unit id="IDS_Lambda"> <source>lambda expression</source> <target state="translated">výraz lambda</target> <note /> </trans-unit> <trans-unit id="IDS_Collection"> <source>collection</source> <target state="translated">kolekce</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePropertyAccessorMods"> <source>access modifiers on properties</source> <target state="translated">modifikátory přístupu pro vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExternAlias"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureIterators"> <source>iterators</source> <target state="translated">iterátory</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefault"> <source>default operator</source> <target state="translated">výchozí operátor</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDefaultLiteral"> <source>default literal</source> <target state="translated">výchozí literál</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePrivateProtected"> <source>private protected</source> <target state="translated">private protected</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullable"> <source>nullable types</source> <target state="translated">typy s povolenou hodnotou null</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePatternMatching"> <source>pattern matching</source> <target state="translated">porovnávání vzorů</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedAccessor"> <source>expression body property accessor</source> <target state="translated">přístupový objekt vlastnosti textu výrazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedDeOrConstructor"> <source>expression body constructor and destructor</source> <target state="translated">konstruktor a destruktor textu výrazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureThrowExpression"> <source>throw expression</source> <target state="translated">výraz throw</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitArray"> <source>implicitly typed array</source> <target state="translated">implicitně typované pole</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureImplicitLocal"> <source>implicitly typed local variable</source> <target state="translated">implicitně typovaná lokální proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAnonymousTypes"> <source>anonymous types</source> <target state="translated">anonymní typy</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAutoImplementedProperties"> <source>automatically implemented properties</source> <target state="translated">automaticky implementované vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadonlyAutoImplementedProperties"> <source>readonly automatically implemented properties</source> <target state="translated">automaticky implementované vlastnosti jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureObjectInitializer"> <source>object initializer</source> <target state="translated">inicializátor objektu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureCollectionInitializer"> <source>collection initializer</source> <target state="translated">inicializátor kolekce</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureQueryExpression"> <source>query expression</source> <target state="translated">výraz dotazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExtensionMethod"> <source>extension method</source> <target state="translated">metoda rozšíření</target> <note /> </trans-unit> <trans-unit id="IDS_FeaturePartialMethod"> <source>partial method</source> <target state="translated">částečná metoda</target> <note /> </trans-unit> <trans-unit id="IDS_SK_METHOD"> <source>method</source> <target state="translated">metoda</target> <note /> </trans-unit> <trans-unit id="IDS_SK_TYPE"> <source>type</source> <target state="translated">typ</target> <note /> </trans-unit> <trans-unit id="IDS_SK_NAMESPACE"> <source>namespace</source> <target state="translated">obor názvů</target> <note /> </trans-unit> <trans-unit id="IDS_SK_FIELD"> <source>field</source> <target state="translated">pole</target> <note /> </trans-unit> <trans-unit id="IDS_SK_PROPERTY"> <source>property</source> <target state="translated">vlastnost</target> <note /> </trans-unit> <trans-unit id="IDS_SK_UNKNOWN"> <source>element</source> <target state="translated">element</target> <note /> </trans-unit> <trans-unit id="IDS_SK_VARIABLE"> <source>variable</source> <target state="translated">proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_SK_LABEL"> <source>label</source> <target state="translated">popisek</target> <note /> </trans-unit> <trans-unit id="IDS_SK_EVENT"> <source>event</source> <target state="translated">událost</target> <note /> </trans-unit> <trans-unit id="IDS_SK_TYVAR"> <source>type parameter</source> <target state="translated">parametr typu</target> <note /> </trans-unit> <trans-unit id="IDS_SK_ALIAS"> <source>using alias</source> <target state="translated">alias using</target> <note /> </trans-unit> <trans-unit id="IDS_SK_EXTERNALIAS"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="IDS_SK_CONSTRUCTOR"> <source>constructor</source> <target state="translated">konstruktor</target> <note /> </trans-unit> <trans-unit id="IDS_FOREACHLOCAL"> <source>foreach iteration variable</source> <target state="translated">iterační proměnná foreach</target> <note /> </trans-unit> <trans-unit id="IDS_FIXEDLOCAL"> <source>fixed variable</source> <target state="translated">pevná proměnná</target> <note /> </trans-unit> <trans-unit id="IDS_USINGLOCAL"> <source>using variable</source> <target state="translated">proměnná using</target> <note /> </trans-unit> <trans-unit id="IDS_Contravariant"> <source>contravariant</source> <target state="translated">kontravariant</target> <note /> </trans-unit> <trans-unit id="IDS_Contravariantly"> <source>contravariantly</source> <target state="translated">kontravariantně</target> <note /> </trans-unit> <trans-unit id="IDS_Covariant"> <source>covariant</source> <target state="translated">kovariant</target> <note /> </trans-unit> <trans-unit id="IDS_Covariantly"> <source>covariantly</source> <target state="translated">kovariantně</target> <note /> </trans-unit> <trans-unit id="IDS_Invariantly"> <source>invariantly</source> <target state="translated">invariantně</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDynamic"> <source>dynamic</source> <target state="translated">dynamický</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNamedArgument"> <source>named argument</source> <target state="translated">pojmenovaný argument</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOptionalParameter"> <source>optional parameter</source> <target state="translated">volitelný parametr</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExceptionFilter"> <source>exception filter</source> <target state="translated">filtr výjimky</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTypeVariance"> <source>type variance</source> <target state="translated">odchylka typu</target> <note /> </trans-unit> <trans-unit id="NotSameNumberParameterTypesAndRefKinds"> <source>Given {0} parameter types and {1} parameter ref kinds. These arrays must have the same length.</source> <target state="translated">Předal se určitý počet parametrů ({0}) a jiný počet druhů odkazů na parametry ({1}). Tato pole musí být stejně velká.</target> <note /> </trans-unit> <trans-unit id="OutIsNotValidForReturn"> <source>'RefKind.Out' is not a valid ref kind for a return type.</source> <target state="translated">RefKind.Out není platný druh odkazu pro návratový typ.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFound"> <source>SyntaxTree is not part of the compilation</source> <target state="translated">SyntaxTree není součástí kompilace.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeNotFoundToRemove"> <source>SyntaxTree is not part of the compilation, so it cannot be removed</source> <target state="translated">SyntaxTree není součástí kompilace, takže se nedá odebrat.</target> <note /> </trans-unit> <trans-unit id="WRN_CaseConstantNamedUnderscore"> <source>The name '_' refers to the constant, not the discard pattern. Use 'var _' to discard the value, or '@_' to refer to a constant by that name.</source> <target state="translated">Název „_“ odkazuje na konstantu, ne na vzor discard. Zadáním „var _“ hodnotu zahodíte a zadáním „@_“ nastavíte pod tímto názvem odkaz na konstantu.</target> <note /> </trans-unit> <trans-unit id="WRN_CaseConstantNamedUnderscore_Title"> <source>Do not use '_' for a case constant.</source> <target state="translated">Nepoužívejte „_“ jako konstantu case.</target> <note /> </trans-unit> <trans-unit id="WRN_ConstOutOfRangeChecked"> <source>Constant value '{0}' may overflow '{1}' at runtime (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnota {0} může při běhu přetéct {1} (pro přepis použijte syntaxi unchecked).</target> <note /> </trans-unit> <trans-unit id="WRN_ConstOutOfRangeChecked_Title"> <source>Constant value may overflow at runtime (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnota může při běhu přetéct (pro přepis použijte syntaxi unchecked)</target> <note /> </trans-unit> <trans-unit id="WRN_ConvertingNullableToNonNullable"> <source>Converting null literal or possible null value to non-nullable type.</source> <target state="translated">Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_ConvertingNullableToNonNullable_Title"> <source>Converting null literal or possible null value to non-nullable type.</source> <target state="translated">Literál s hodnotou null nebo s možnou hodnotou null se převádí na typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_DisallowNullAttributeForbidsMaybeNullAssignment"> <source>A possible null value may not be used for a type marked with [NotNull] or [DisallowNull]</source> <target state="translated">Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull].</target> <note /> </trans-unit> <trans-unit id="WRN_DisallowNullAttributeForbidsMaybeNullAssignment_Title"> <source>A possible null value may not be used for a type marked with [NotNull] or [DisallowNull]</source> <target state="translated">Možnou hodnotu null není možné použít pro typ označený jako [NotNull] nebo [DisallowNull].</target> <note /> </trans-unit> <trans-unit id="WRN_DoesNotReturnMismatch"> <source>Method '{0}' lacks `[DoesNotReturn]` annotation to match implemented or overridden member.</source> <target state="translated">Metodě {0} chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_DoesNotReturnMismatch_Title"> <source>Method lacks `[DoesNotReturn]` annotation to match implemented or overridden member.</source> <target state="translated">Metodě chybí poznámka [DoesNotReturn], která by odpovídala implementovanému nebo přepsanému členu</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList"> <source>'{0}' is already listed in the interface list on type '{1}' with different nullability of reference types.</source> <target state="translated">Položka {0} je už uvedená v seznamu rozhraní u typu {1} s různou možností použití hodnoty null u typů odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList_Title"> <source>Interface is already listed in the interface list with different nullability of reference types.</source> <target state="translated">Rozhraní je už uvedené v seznamu rozhraní s různou možností použití hodnoty null u typů odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration"> <source>Generator '{0}' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">Generátor {0} nemohl vygenerovat zdroj. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}.</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">Generátor vyvolal následující výjimku: {0}.</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringGeneration_Title"> <source>Generator failed to generate source.</source> <target state="translated">Generátoru se nepovedlo vygenerovat zdroj</target> <note /> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization"> <source>Generator '{0}' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was of type '{1}' with message '{2}'</source> <target state="translated">Generátor {0} se nepovedlo inicializovat. V důsledku toho může docházet k chybám kompilace a generátor nebude přispívat na výstup. Výjimka měla typ {1} se zprávou {2}.</target> <note>{0} is the name of the generator that failed. {1} is the type of exception that was thrown {2} is the message in the exception</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Description"> <source>Generator threw the following exception: '{0}'.</source> <target state="translated">Generátor vyvolal následující výjimku: {0}.</target> <note>{0} is the string representation of the exception that was thrown.</note> </trans-unit> <trans-unit id="WRN_GeneratorFailedDuringInitialization_Title"> <source>Generator failed to initialize.</source> <target state="translated">Generátor se nepovedlo inicializovat</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesConstant"> <source>The given expression always matches the provided constant.</source> <target state="translated">Daný výraz vždy odpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesConstant_Title"> <source>The given expression always matches the provided constant.</source> <target state="translated">Daný výraz vždy odpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesPattern"> <source>The given expression always matches the provided pattern.</source> <target state="translated">Daný výraz vždy odpovídá zadanému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionAlwaysMatchesPattern_Title"> <source>The given expression always matches the provided pattern.</source> <target state="translated">Daný výraz vždy odpovídá zadanému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionNeverMatchesPattern"> <source>The given expression never matches the provided pattern.</source> <target state="translated">Daný výraz nikdy neodpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_GivenExpressionNeverMatchesPattern_Title"> <source>The given expression never matches the provided pattern.</source> <target state="translated">Daný výraz nikdy neodpovídá zadané konstantě.</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitCopyInReadOnlyMember"> <source>Call to non-readonly member '{0}' from a 'readonly' member results in an implicit copy of '{1}'.</source> <target state="translated">Volání člena {0}, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ImplicitCopyInReadOnlyMember_Title"> <source>Call to non-readonly member from a 'readonly' member results in an implicit copy.</source> <target state="translated">Volání člena, který nemá modifikátor readonly, ze člena s modifikátorem readonly má za následek implicitní kopii.</target> <note /> </trans-unit> <trans-unit id="WRN_IsPatternAlways"> <source>An expression of type '{0}' always matches the provided pattern.</source> <target state="translated">Výraz typu {0} vždy odpovídá poskytnutému vzoru.</target> <note /> </trans-unit> <trans-unit id="WRN_IsPatternAlways_Title"> <source>The input always matches the provided pattern.</source> <target state="translated">Vstup vždy odpovídá zadanému vzoru</target> <note /> </trans-unit> <trans-unit id="WRN_IsTypeNamedUnderscore"> <source>The name '_' refers to the type '{0}', not the discard pattern. Use '@_' for the type, or 'var _' to discard.</source> <target state="translated">Název „_“ odkazuje na typ {0}, ne vzor discard. Použijte „@_“ pro tento typ nebo „var _“ pro zahození.</target> <note /> </trans-unit> <trans-unit id="WRN_IsTypeNamedUnderscore_Title"> <source>Do not use '_' to refer to the type in an is-type expression.</source> <target state="translated">Nepoužívejte „_“ jako odkaz na typ ve výrazu is-type.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNull"> <source>Member '{0}' must have a non-null value when exiting.</source> <target state="translated">Člen {0} musí mít při ukončení hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullBadMember"> <source>Member '{0}' cannot be used in this attribute.</source> <target state="translated">Člen {0} se v tomto atributu nedá použít.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullBadMember_Title"> <source>Member cannot be used in this attribute.</source> <target state="translated">Člen se v tomto atributu nedá použít.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullWhen"> <source>Member '{0}' must have a non-null value when exiting with '{1}'.</source> <target state="translated">Člen {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNullWhen_Title"> <source>Member must have a non-null value when exiting in some condition.</source> <target state="translated">Člen musí mít při ukončení za určité podmínky hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_MemberNotNull_Title"> <source>Member must have a non-null value when exiting.</source> <target state="translated">Člen musí mít při ukončení hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotation"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.</source> <target state="translated">Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.</source> <target state="translated">Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode_Title"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.</source> <target state="translated">Poznámka pro typy odkazů s možnou hodnotou null by se měla používat jenom v kódu v rámci kontextu poznámek #nullable. Automaticky vygenerovaný kód vyžaduje explicitní direktivu #nullable ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingNonNullTypesContextForAnnotation_Title"> <source>The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.</source> <target state="translated">Poznámka u typů odkazů s možnou hodnotou null by se měla v kódu používat jenom v kontextu poznámek #nullable.</target> <note /> </trans-unit> <trans-unit id="WRN_NullAsNonNullable"> <source>Cannot convert null literal to non-nullable reference type.</source> <target state="translated">Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullAsNonNullable_Title"> <source>Cannot convert null literal to non-nullable reference type.</source> <target state="translated">Literál null nejde převést na odkazový typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceArgument"> <source>Possible null reference argument for parameter '{0}' in '{1}'.</source> <target state="translated">V parametru {0} v {1} může být argument s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceArgument_Title"> <source>Possible null reference argument.</source> <target state="translated">Může jít o argument s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceAssignment"> <source>Possible null reference assignment.</source> <target state="translated">Může jít o přiřazení s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceAssignment_Title"> <source>Possible null reference assignment.</source> <target state="translated">Může jít o přiřazení s odkazem null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceInitializer"> <source>Object or collection initializer implicitly dereferences possibly null member '{0}'.</source> <target state="translated">Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi {0}, který může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceInitializer_Title"> <source>Object or collection initializer implicitly dereferences possibly null member.</source> <target state="translated">Inicializátor objektu nebo kolekce implicitně přistupuje přes ukazatel ke členovi, který může být null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReceiver"> <source>Dereference of a possibly null reference.</source> <target state="translated">Přístup přes ukazatel k možnému odkazu s hodnotou null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReceiver_Title"> <source>Dereference of a possibly null reference.</source> <target state="translated">Přístup přes ukazatel k možnému odkazu s hodnotou null</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReturn"> <source>Possible null reference return.</source> <target state="translated">Může jít o vrácený odkaz null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullReferenceReturn_Title"> <source>Possible null reference return.</source> <target state="translated">Může jít o vrácený odkaz null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgument"> <source>Argument of type '{0}' cannot be used for parameter '{2}' of type '{1}' in '{3}' due to differences in the nullability of reference types.</source> <target state="translated">Argument typu {0} nejde použít pro parametr {2} typu {1} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgumentForOutput"> <source>Argument of type '{0}' cannot be used as an output of type '{1}' for parameter '{2}' in '{3}' due to differences in the nullability of reference types.</source> <target state="translated">Argument typu {0} nejde použít jako výstup typu {1} pro parametr {2} v {3} z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgumentForOutput_Title"> <source>Argument cannot be used as an output for parameter due to differences in the nullability of reference types.</source> <target state="translated">Argument nejde použít jako výstup pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInArgument_Title"> <source>Argument cannot be used for parameter due to differences in the nullability of reference types.</source> <target state="translated">Argument nejde použít pro parametr z důvodu rozdílů v možnostech použití hodnoty null u odkazových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInAssignment"> <source>Nullability of reference types in value of type '{0}' doesn't match target type '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v hodnotě typu {0} neodpovídá cílovému typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInAssignment_Title"> <source>Nullability of reference types in value doesn't match target type.</source> <target state="translated">Typ odkazu s možnou hodnotou null v hodnotě neodpovídá cílovému typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnImplicitImplementation"> <source>Nullability in constraints for type parameter '{0}' of method '{1}' doesn't match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead.</source> <target state="translated">Možná hodnota null v omezení parametru typu {0} metody {1} neodpovídá omezením parametru typu {2} metody rozhraní {3}. Zkuste raději použít explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnImplicitImplementation_Title"> <source>Nullability in constraints for type parameter doesn't match the constraints for type parameter in implicitly implemented interface method'.</source> <target state="translated">Možná hodnota null v omezeních parametru typu neodpovídá omezením parametru typu v implicitně implementované metodě rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnPartialImplementation"> <source>Partial method declarations of '{0}' have inconsistent nullability in constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace metod {0} mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInConstraintsOnPartialImplementation_Title"> <source>Partial method declarations have inconsistent nullability in constraints for type parameter</source> <target state="translated">Částečné deklarace metod mají nekonzistentní možnost použití hodnoty null v omezeních parametru typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInExplicitlyImplementedInterface"> <source>Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.</source> <target state="translated">Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInExplicitlyImplementedInterface_Title"> <source>Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type.</source> <target state="translated">Možnost použití hodnoty null u typů odkazů v explicitním specifikátoru rozhraní neodpovídá rozhraní implementovanému podle tohoto typu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInInterfaceImplementedByBase"> <source>'{0}' does not implement interface member '{1}'. Nullability of reference types in interface implemented by the base type doesn't match.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInInterfaceImplementedByBase_Title"> <source>Type does not implement interface member. Nullability of reference types in interface implemented by the base type doesn't match.</source> <target state="translated">Typ neimplementuje člen rozhraní. Možnost použití hodnoty null u typů odkazů v rozhraní implementovaném podle základního typu se neshoduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOfTargetDelegate"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match the target delegate '{2}' (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v typu parametru {0} z {1} neodpovídají cílovému delegátu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOfTargetDelegate_Title"> <source>Nullability of reference types in type of parameter doesn't match the target delegate (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v typu parametru neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnOverride"> <source>Nullability of reference types in type of parameter '{0}' doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnOverride_Title"> <source>Nullability of reference types in type of parameter doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnPartial"> <source>Nullability of reference types in type of parameter '{0}' doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInParameterTypeOnPartial_Title"> <source>Nullability of reference types in type of parameter doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOfTargetDelegate"> <source>Nullability of reference types in return type of '{0}' doesn't match the target delegate '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v návratovém typu {0} neodpovídají cílovému delegátu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOfTargetDelegate_Title"> <source>Nullability of reference types in return type doesn't match the target delegate (possibly because of nullability attributes).</source> <target state="translated">Typy odkazů s možnou hodnotou null v návratovém typu neodpovídají cílovému delegátu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation"> <source>Nullability of reference types in return type doesn't match implemented member '{0}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation"> <source>Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnOverride"> <source>Nullability of reference types in return type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnOverride_Title"> <source>Nullability of reference types in return type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnPartial"> <source>Nullability of reference types in return type doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInReturnTypeOnPartial_Title"> <source>Nullability of reference types in return type doesn't match partial method declaration.</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá deklaraci částečné metody</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnExplicitImplementation"> <source>Nullability of reference types in type doesn't match implemented member '{0}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type doesn't match implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnImplicitImplementation"> <source>Nullability of reference types in type of '{0}' doesn't match implicitly implemented member '{1}'.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu {0} neodpovídá implicitně implementovanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type doesn't match implicitly implemented member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá implicitně implementovanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnOverride"> <source>Nullability of reference types in type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeOnOverride_Title"> <source>Nullability of reference types in type doesn't match overridden member.</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu neodpovídá přepsanému členu.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterConstraint"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. Nullability of type argument '{3}' doesn't match constraint type '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ argumentu {3} s možnou hodnotou null neodpovídá typu omezení {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match constraint type.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá typu omezení.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterNotNullConstraint"> <source>The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'notnull' constraint.</source> <target state="translated">Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Argument typu {2} s možnou hodnotou null neodpovídá omezení notnull.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterNotNullConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'notnull' constraint.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Argument typu s možnou hodnotou null neodpovídá omezení notnull.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint"> <source>The type '{2}' cannot be used as type parameter '{1}' in the generic type or method '{0}'. Nullability of type argument '{2}' doesn't match 'class' constraint.</source> <target state="translated">Typ {2} nejde použít jako parametr typu {1} v obecném typu nebo metodě {0}. Typ argumentu {2} s možnou hodnotou null neodpovídá omezení třídy.</target> <note /> </trans-unit> <trans-unit id="WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint_Title"> <source>The type cannot be used as type parameter in the generic type or method. Nullability of type argument doesn't match 'class' constraint.</source> <target state="translated">Typ nejde použít jako parametr typu v obecném typu nebo metodě. Typ argumentu s možnou hodnotou null neodpovídá omezení třídy.</target> <note /> </trans-unit> <trans-unit id="WRN_NullableValueTypeMayBeNull"> <source>Nullable value type may be null.</source> <target state="translated">Typ hodnoty, která připouští hodnotu null, nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WRN_NullableValueTypeMayBeNull_Title"> <source>Nullable value type may be null.</source> <target state="translated">Typ hodnoty, která připouští hodnotu null, nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParamUnassigned"> <source>The out parameter '{0}' must be assigned to before control leaves the current method</source> <target state="translated">Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení.</target> <note /> </trans-unit> <trans-unit id="WRN_ParamUnassigned_Title"> <source>An out parameter must be assigned to before control leaves the method</source> <target state="translated">Parametr out se musí přiřadit ještě předtím, než metoda předá řízení</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterConditionallyDisallowsNull"> <source>Parameter '{0}' must have a non-null value when exiting with '{1}'.</source> <target state="translated">Parametr {0} musí mít při ukončení s návratovou hodnotou {1} hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterConditionallyDisallowsNull_Title"> <source>Parameter must have a non-null value when exiting in some condition.</source> <target state="translated">Parametr musí mít při ukončení za určité podmínky hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterDisallowsNull"> <source>Parameter '{0}' must have a non-null value when exiting.</source> <target state="translated">Parametr {0} musí mít při ukončení hodnotu jinou než null.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterDisallowsNull_Title"> <source>Parameter must have a non-null value when exiting.</source> <target state="translated">Parametr musí mít při ukončení hodnotu jinou než null</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterIsStaticClass"> <source>'{0}': static types cannot be used as parameters</source> <target state="translated">{0}: Statické typy nejde používat jako parametry.</target> <note /> </trans-unit> <trans-unit id="WRN_ParameterIsStaticClass_Title"> <source>Static types cannot be used as parameters</source> <target state="translated">Statické typy se nedají používat jako parametry</target> <note /> </trans-unit> <trans-unit id="WRN_PrecedenceInversion"> <source>Operator '{0}' cannot be used here due to precedence. Use parentheses to disambiguate.</source> <target state="translated">Operátor {0} se tady nedá použít kvůli prioritám. Odstraňte nejednoznačnost pomocí závorek.</target> <note /> </trans-unit> <trans-unit id="WRN_PrecedenceInversion_Title"> <source>Operator cannot be used here due to precedence.</source> <target state="translated">Operátor se tady nedá použít kvůli prioritám</target> <note /> </trans-unit> <trans-unit id="WRN_PatternNotPublicOrNotInstance"> <source>'{0}' does not implement the '{1}' pattern. '{2}' is not a public instance or extension method.</source> <target state="translated">{0} neimplementuje vzor {1}. {2} není veřejná metoda instance nebo rozšíření.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternNotPublicOrNotInstance_Title"> <source>Type does not implement the collection pattern; member is is not a public instance or extension method.</source> <target state="translated">Typ neimplementuje vzor kolekce. Člen není veřejná metoda instance nebo rozšíření</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeIsStaticClass"> <source>'{0}': static types cannot be used as return types</source> <target state="translated">{0}: Statické typy nejde používat jako typy vracených hodnot.</target> <note /> </trans-unit> <trans-unit id="WRN_ReturnTypeIsStaticClass_Title"> <source>Static types cannot be used as return types</source> <target state="translated">Statické typy se nedají používat jako typy vracených hodnot</target> <note /> </trans-unit> <trans-unit id="WRN_ShouldNotReturn"> <source>A method marked [DoesNotReturn] should not return.</source> <target state="translated">Metoda označená jako [DoesNotReturn] by neměla vracet hodnotu</target> <note /> </trans-unit> <trans-unit id="WRN_ShouldNotReturn_Title"> <source>A method marked [DoesNotReturn] should not return.</source> <target state="translated">Metoda označená jako [DoesNotReturn] by se neměla ukončit standardním způsobem</target> <note /> </trans-unit> <trans-unit id="WRN_StaticInAsOrIs"> <source>The second operand of an 'is' or 'as' operator may not be static type '{0}'</source> <target state="translated">Druhý operand operátoru is nebo as nesmí být statického typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_StaticInAsOrIs_Title"> <source>The second operand of an 'is' or 'as' operator may not be a static type</source> <target state="translated">Druhý operand operátoru is nebo as nesmí být statického typu</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustive"> <source>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.</source> <target state="translated">Výraz switch nezachycuje všechny možné hodnoty vstupního typu (není úplný). Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNull"> <source>The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered.</source> <target state="translated">Výraz switch nezachycuje všechny některé vstupy null (není úplný). Nezachycuje například vzor {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNullWithWhen"> <source>The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '{0}' is not covered. However, a pattern with a 'when' clause might successfully match this value.</source> <target state="translated">Výraz switch nezpracovává některé vstupy null (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNullWithWhen_Title"> <source>The switch expression does not handle some null inputs.</source> <target state="translated">Výraz switch nezpracovává některé vstupy s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveForNull_Title"> <source>The switch expression does not handle some null inputs.</source> <target state="translated">Výraz switch nezpracovává některé vstupy s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithWhen"> <source>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.</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty typu svého vstupu (není úplný). Například vzor {0} není vyřešený. Vzor s klauzulí when však může této hodnotě úspěšně odpovídat.</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustiveWithWhen_Title"> <source>The switch expression does not handle all possible values of its input type (it is not exhaustive).</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný).</target> <note /> </trans-unit> <trans-unit id="WRN_SwitchExpressionNotExhaustive_Title"> <source>The switch expression does not handle all possible values of its input type (it is not exhaustive).</source> <target state="translated">Výraz switch nezpracovává všechny možné hodnoty svého vstupního typu (není úplný)</target> <note /> </trans-unit> <trans-unit id="WRN_ThrowPossibleNull"> <source>Thrown value may be null.</source> <target state="translated">Vyvolaná hodnota může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_ThrowPossibleNull_Title"> <source>Thrown value may be null.</source> <target state="translated">Vyvolaná hodnota může být null.</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' doesn't match implemented member '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} neodpovídá implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation"> <source>Nullability of reference types in type of parameter '{0}' of '{1}' doesn't match implicitly implemented member '{2}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru {0} z {1} neodpovídá implicitně implementovanému členu {2} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v typu parametru neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride"> <source>Nullability of type of parameter '{0}' doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u typu parametru {0} neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride_Title"> <source>Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u typu parametru neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation"> <source>Nullability of reference types in return type doesn't match implemented member '{0}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null ve vráceném typu neodpovídá implementovanému členu {0} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation"> <source>Nullability of reference types in return type of '{0}' doesn't match implicitly implemented member '{1}' (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu {0} neodpovídá implicitně implementovanému členu {1} (pravděpodobně kvůli atributům možnosti použití hodnoty null).</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation_Title"> <source>Nullability of reference types in return type doesn't match implicitly implemented member (possibly because of nullability attributes).</source> <target state="translated">Typ odkazu s možnou hodnotou null v návratovém typu neodpovídá implicitně implementovanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride"> <source>Nullability of return type doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride_Title"> <source>Nullability of return type doesn't match overridden member (possibly because of nullability attributes).</source> <target state="translated">Možnost použití hodnoty null u návratového typu neodpovídá přepsanému členu (pravděpodobně kvůli atributům možnosti použití hodnoty null)</target> <note /> </trans-unit> <trans-unit id="WRN_TupleBinopLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified on the other side of the tuple == or != operator.</source> <target state="translated">Název elementu řazené kolekce členů {0} se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleBinopLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified on the other side of the tuple == or != operator.</source> <target state="translated">Název elementu řazené kolekce členů se ignoruje, protože na druhé straně operátoru == nebo != řazené kolekce členů je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterMethodTypeParameter"> <source>Type parameter '{0}' has the same name as the type parameter from outer method '{1}'</source> <target state="translated">Parametr typu {0} má stejný název jako parametr typu z vnější metody {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterMethodTypeParameter_Title"> <source>Type parameter has the same type as the type parameter from outer method.</source> <target state="translated">Parametr typu má stejný typ jako parametr typu z vnější metody.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThis"> <source>Field '{0}' must be fully assigned before control is returned to the caller</source> <target state="translated">Před předáním řízení volající proceduře musí být pole {0} plně přiřazené.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThisAutoProperty"> <source>Auto-implemented property '{0}' must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu modulu musí být plně přiřazená automaticky implementovaná vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThisAutoProperty_Title"> <source>An auto-implemented property must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu se musí plně přiřadit automaticky implementovaná vlastnost</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedThis_Title"> <source>Fields of a struct must be fully assigned in a constructor before control is returned to the caller</source> <target state="translated">Před vrácením řízení volajícímu se musí v konstruktoru plně přiřadit pole struktury</target> <note /> </trans-unit> <trans-unit id="WRN_UnboxPossibleNull"> <source>Unboxing a possibly null value.</source> <target state="translated">Rozbalení možné hodnoty null</target> <note /> </trans-unit> <trans-unit id="WRN_UnboxPossibleNull_Title"> <source>Unboxing a possibly null value.</source> <target state="translated">Rozbalení možné hodnoty null</target> <note /> </trans-unit> <trans-unit id="WRN_UnconsumedEnumeratorCancellationAttributeUsage"> <source>The EnumeratorCancellationAttribute applied to parameter '{0}' will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable</source> <target state="translated">EnumeratorCancellationAttribute, který se používá u parametru {0}, nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable.</target> <note /> </trans-unit> <trans-unit id="WRN_UnconsumedEnumeratorCancellationAttributeUsage_Title"> <source>The EnumeratorCancellationAttribute will have no effect. The attribute is only effective on a parameter of type CancellationToken in an async-iterator method returning IAsyncEnumerable</source> <target state="translated">EnumeratorCancellationAttribute nebude mít žádný účinek. Tento atribut je platný jenom u parametru typu CancellationToken v metodě async-iterator, která vrací IAsyncEnumerable.</target> <note /> </trans-unit> <trans-unit id="WRN_UndecoratedCancellationTokenParameter"> <source>Async-iterator '{0}' has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator' will be unconsumed</source> <target state="translated">Asynchronní iterátor {0} má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator se nespotřebuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UndecoratedCancellationTokenParameter_Title"> <source>Async-iterator member has one or more parameters of type 'CancellationToken' but none of them is decorated with the 'EnumeratorCancellation' attribute, so the cancellation token parameter from the generated 'IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator' will be unconsumed</source> <target state="translated">Člen asynchronního iterátoru má jeden nebo více parametrů typu CancellationToken, ale žádný z nich není dekorovaný atributem EnumeratorCancellation, takže parametr tokenu zrušení z vygenerovaného výrazu IAsyncEnumerable&lt;&gt;.GetAsyncEnumerator se nespotřebuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UninitializedNonNullableField"> <source>Non-nullable {0} '{1}' must contain a non-null value when exiting constructor. Consider declaring the {0} as nullable.</source> <target state="translated">Proměnná {0} {1}, která nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat {0} jako proměnnou s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_UninitializedNonNullableField_Title"> <source>Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.</source> <target state="translated">Pole, které nemůže být null, musí při ukončování konstruktoru obsahovat hodnotu, která není null. Zvažte možnost deklarovat ho jako pole s možnou hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreadRecordParameter"> <source>Parameter '{0}' is unread. Did you forget to use it to initialize the property with that name?</source> <target state="translated">Parametr {0} se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem?</target> <note /> </trans-unit> <trans-unit id="WRN_UnreadRecordParameter_Title"> <source>Parameter is unread. Did you forget to use it to initialize the property with that name?</source> <target state="translated">Parametr se nepřečetl. Nezapomněli jste ho použít k inicializaci vlastnosti s daným názvem?</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolation"> <source>Use of unassigned local variable '{0}'</source> <target state="translated">Použila se nepřiřazená lokální proměnná {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationField"> <source>Use of possibly unassigned field '{0}'</source> <target state="translated">Použila se možná nepřiřazené pole {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationField_Title"> <source>Use of possibly unassigned field</source> <target state="translated">Použilo se pravděpodobně nepřiřazené pole</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationOut"> <source>Use of unassigned out parameter '{0}'</source> <target state="translated">Použil se nepřiřazený parametr out {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationOut_Title"> <source>Use of unassigned out parameter</source> <target state="translated">Použil se nepřiřazený parametr out</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationProperty"> <source>Use of possibly unassigned auto-implemented property '{0}'</source> <target state="translated">Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0}</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationProperty_Title"> <source>Use of possibly unassigned auto-implemented property</source> <target state="translated">Použily se pravděpodobně nepřiřazené automaticky implementované vlastnosti</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationThis"> <source>The 'this' object cannot be used before all of its fields have been assigned</source> <target state="translated">Objekt this se nedá použít, dokud se nepřiřadí všechna jeho pole.</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolationThis_Title"> <source>The 'this' object cannot be used in a constructor before all of its fields have been assigned</source> <target state="translated">Objekt this se v konstruktoru nedá použít, dokud se nepřiřadí všechna jeho pole</target> <note /> </trans-unit> <trans-unit id="WRN_UseDefViolation_Title"> <source>Use of unassigned local variable</source> <target state="translated">Použila se nepřiřazená lokální proměnná</target> <note /> </trans-unit> <trans-unit id="XML_InvalidToken"> <source>The character(s) '{0}' cannot be used at this location.</source> <target state="translated">Znaky {0} se na tomto místě nedají použít.</target> <note /> </trans-unit> <trans-unit id="XML_IncorrectComment"> <source>Incorrect syntax was used in a comment.</source> <target state="translated">V komentáři se používá nesprávná syntaxe.</target> <note /> </trans-unit> <trans-unit id="XML_InvalidCharEntity"> <source>An invalid character was found inside an entity reference.</source> <target state="translated">Uvnitř odkazu na entitu se našel neplatný znak.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedEndOfTag"> <source>Expected '&gt;' or '/&gt;' to close tag '{0}'.</source> <target state="translated">Očekával se řetězec &gt; nebo /&gt; uzavírající značku {0}.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedIdentifier"> <source>An identifier was expected.</source> <target state="translated">Očekával se identifikátor.</target> <note /> </trans-unit> <trans-unit id="XML_InvalidUnicodeChar"> <source>Invalid unicode character.</source> <target state="translated">Neplatný znak unicode</target> <note /> </trans-unit> <trans-unit id="XML_InvalidWhitespace"> <source>Whitespace is not allowed at this location.</source> <target state="translated">Prázdný znak není v tomto místě povolený.</target> <note /> </trans-unit> <trans-unit id="XML_LessThanInAttributeValue"> <source>The character '&lt;' cannot be used in an attribute value.</source> <target state="translated">Znak &lt; se nedá použít v hodnotě atributu.</target> <note /> </trans-unit> <trans-unit id="XML_MissingEqualsAttribute"> <source>Missing equals sign between attribute and attribute value.</source> <target state="translated">Mezi atributem a jeho hodnotou chybí znaménko rovná se.</target> <note /> </trans-unit> <trans-unit id="XML_RefUndefinedEntity_1"> <source>Reference to undefined entity '{0}'.</source> <target state="translated">Odkaz na nedefinovanou entitu {0}</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNoStartQuote"> <source>A string literal was expected, but no opening quotation mark was found.</source> <target state="translated">Očekával se řetězcový literál, ale nenašly se úvodní uvozovky.</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNoEndQuote"> <source>Missing closing quotation mark for string literal.</source> <target state="translated">U řetězcového literálu chybí koncové uvozovky.</target> <note /> </trans-unit> <trans-unit id="XML_StringLiteralNonAsciiQuote"> <source>Non-ASCII quotations marks may not be used around string literals.</source> <target state="translated">U řetězcových literálů se nesmí používat jiné uvozovky než ASCII.</target> <note /> </trans-unit> <trans-unit id="XML_EndTagNotExpected"> <source>End tag was not expected at this location.</source> <target state="translated">Na tomto místě se neočekávala koncová značka.</target> <note /> </trans-unit> <trans-unit id="XML_ElementTypeMatch"> <source>End tag '{0}' does not match the start tag '{1}'.</source> <target state="translated">Koncová značka {0} neodpovídá počáteční značce {1}.</target> <note /> </trans-unit> <trans-unit id="XML_EndTagExpected"> <source>Expected an end tag for element '{0}'.</source> <target state="translated">Očekávala se koncová značka pro element {0}.</target> <note /> </trans-unit> <trans-unit id="XML_WhitespaceMissing"> <source>Required white space was missing.</source> <target state="translated">Chybí požadovaná mezera.</target> <note /> </trans-unit> <trans-unit id="XML_ExpectedEndOfXml"> <source>Unexpected character at this location.</source> <target state="translated">Neočekávaný znak na tomto místě</target> <note /> </trans-unit> <trans-unit id="XML_CDataEndTagNotAllowed"> <source>The literal string ']]&gt;' is not allowed in element content.</source> <target state="translated">V obsahu elementu není povolený řetězec literálu ]]&gt;.</target> <note /> </trans-unit> <trans-unit id="XML_DuplicateAttribute"> <source>Duplicate '{0}' attribute</source> <target state="translated">Duplicitní atribut {0}</target> <note /> </trans-unit> <trans-unit id="ERR_NoMetadataFile"> <source>Metadata file '{0}' could not be found</source> <target state="translated">Soubor metadat {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataReferencesNotSupported"> <source>Metadata references are not supported.</source> <target state="translated">Odkazy v metadatech se nepodporují.</target> <note /> </trans-unit> <trans-unit id="FTL_MetadataCantOpenFile"> <source>Metadata file '{0}' could not be opened -- {1}</source> <target state="translated">Soubor metadat {0} nešel otevřít -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeDef"> <source>The type '{0}' is defined in an assembly that is not referenced. You must add a reference to assembly '{1}'.</source> <target state="translated">Typ {0} je definovaný jako sestavení, na které se neodkazuje. Je nutné přidat odkaz na sestavení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoTypeDefFromModule"> <source>The type '{0}' is defined in a module that has not been added. You must add the module '{1}'.</source> <target state="translated">Typ {0} je definovaný v modulu, který jste nepřidali. Musíte přidat modul {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_OutputWriteFailed"> <source>Could not write to output file '{0}' -- '{1}'</source> <target state="translated">Do výstupního souboru {0} nejde zapisovat -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleEntryPoints"> <source>Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point.</source> <target state="translated">Program má definovaný víc než jeden vstupní bod. V kompilaci použijte /main určující typ, který vstupní bod obsahuje.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinaryOps"> <source>Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'</source> <target state="translated">Operátor {0} nejde použít na operandy typu {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_IntDivByZero"> <source>Division by constant zero</source> <target state="translated">Dělení nulovou konstantou</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexLHS"> <source>Cannot apply indexing with [] to an expression of type '{0}'</source> <target state="translated">Ve výrazu typu {0} nejde použít indexování pomocí hranatých závorek ([]).</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexCount"> <source>Wrong number of indices inside []; expected {0}</source> <target state="translated">Špatné číslo indexu uvnitř []; očekává se {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnaryOp"> <source>Operator '{0}' cannot be applied to operand of type '{1}'</source> <target state="translated">Operátor {0} nejde použít na operand typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisInStaticMeth"> <source>Keyword 'this' is not valid in a static property, static method, or static field initializer</source> <target state="translated">Klíčové slovo this není platné ve statické vlastnosti, ve statické metodě ani ve statickém inicializátoru pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisInBadContext"> <source>Keyword 'this' is not available in the current context</source> <target state="translated">Klíčové slovo this není v aktuálním kontextu k dispozici.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidMainSig"> <source>'{0}' has the wrong signature to be an entry point</source> <target state="translated">{0} nemá správný podpis, takže nemůže být vstupním bodem.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidMainSig_Title"> <source>Method has the wrong signature to be an entry point</source> <target state="translated">Metoda nemá správný podpis, takže nemůže být vstupním bodem.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConv"> <source>Cannot implicitly convert type '{0}' to '{1}'</source> <target state="translated">Typ {0} nejde implicitně převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitConv"> <source>Cannot convert type '{0}' to '{1}'</source> <target state="translated">Typ {0} nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstOutOfRange"> <source>Constant value '{0}' cannot be converted to a '{1}'</source> <target state="translated">Konstantní hodnotu {0} nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigBinaryOps"> <source>Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'</source> <target state="translated">Operátor {0} je nejednoznačný na operandech typu {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigUnaryOp"> <source>Operator '{0}' is ambiguous on an operand of type '{1}'</source> <target state="translated">Operátor {0} je nejednoznačný na operandu typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_InAttrOnOutParam"> <source>An out parameter cannot have the In attribute</source> <target state="translated">Parametr out nemůže obsahovat atribut In.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueCantBeNull"> <source>Cannot convert null to '{0}' because it is a non-nullable value type</source> <target state="translated">Hodnotu null nejde převést na typ {0}, protože se jedná o typ, který nemůže mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="ERR_NoExplicitBuiltinConv"> <source>Cannot convert type '{0}' to '{1}' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion</source> <target state="translated">Typ {0} nejde převést na {1} prostřednictvím převodu odkazu, převodu zabalení, převodu rozbalení, převodu obálky nebo převodu s hodnotou null.</target> <note /> </trans-unit> <trans-unit id="FTL_DebugEmitFailure"> <source>Unexpected error writing debug information -- '{0}'</source> <target state="translated">Neočekávaná chyba při zápisu ladicích informací -- {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisReturnType"> <source>Inconsistent accessibility: return type '{1}' is less accessible than method '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než metoda {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisParamType"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než metoda {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisFieldType"> <source>Inconsistent accessibility: field type '{1}' is less accessible than field '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ pole {1} je míň dostupný než pole {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisPropertyType"> <source>Inconsistent accessibility: property type '{1}' is less accessible than property '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vlastnosti {1} je míň dostupný než vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisIndexerReturn"> <source>Inconsistent accessibility: indexer return type '{1}' is less accessible than indexer '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty indexeru {1} je méně dostupný než indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisIndexerParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than indexer '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisOpReturn"> <source>Inconsistent accessibility: return type '{1}' is less accessible than operator '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než operátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisOpParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than operator '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než operátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisDelegateReturn"> <source>Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ vrácené hodnoty {1} je míň dostupný než delegát {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisDelegateParam"> <source>Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ parametru {1} je míň dostupný než delegát {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBaseClass"> <source>Inconsistent accessibility: base class '{1}' is less accessible than class '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Základní třída {1} je míň dostupná než třída {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBaseInterface"> <source>Inconsistent accessibility: base interface '{1}' is less accessible than interface '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Základní rozhraní {1} je míň dostupné než rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_EventNeedsBothAccessors"> <source>'{0}': event property must have both add and remove accessors</source> <target state="translated">{0}: Vlastnost události musí obsahovat přistupující objekty add i remove.</target> <note /> </trans-unit> <trans-unit id="ERR_EventNotDelegate"> <source>'{0}': event must be of a delegate type</source> <target state="translated">{0}: Událost musí být typu delegát.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedEvent"> <source>The event '{0}' is never used</source> <target state="translated">Událost {0} se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedEvent_Title"> <source>Event is never used</source> <target state="translated">Událost se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceEventInitializer"> <source>'{0}': instance event in interface cannot have initializer</source> <target state="translated">{0}: Událost instance v rozhraní nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventUsage"> <source>The event '{0}' can only appear on the left hand side of += or -= (except when used from within the type '{1}')</source> <target state="translated">Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -= (s výjimkou případu, kdy se používá z typu {1}).</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitEventFieldImpl"> <source>An explicit interface implementation of an event must use event accessor syntax</source> <target state="translated">Explicitní implementace rozhraní události musí používat syntaxi přistupujícího objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonEvent"> <source>'{0}': cannot override; '{1}' is not an event</source> <target state="translated">{0}: Nejde přepsat; {1} není událost.</target> <note /> </trans-unit> <trans-unit id="ERR_AddRemoveMustHaveBody"> <source>An add or remove accessor must have a body</source> <target state="translated">Přistupující objekty add a remove musí mít tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractEventInitializer"> <source>'{0}': abstract event cannot have initializer</source> <target state="translated">{0}: Abstraktní událost nemůže mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedAssemblyName"> <source>The assembly name '{0}' is reserved and cannot be used as a reference in an interactive session</source> <target state="translated">Název sestavení {0} je rezervovaný a nedá se použít jako odkaz v interaktivní relaci.</target> <note /> </trans-unit> <trans-unit id="ERR_ReservedEnumerator"> <source>The enumerator name '{0}' is reserved and cannot be used</source> <target state="translated">Název čítače výčtu {0} je rezervovaný a nedá se použít.</target> <note /> </trans-unit> <trans-unit id="ERR_AsMustHaveReferenceType"> <source>The as operator must be used with a reference type or nullable type ('{0}' is a non-nullable value type)</source> <target state="translated">Operátor as je třeba použít s typem odkazu nebo s typem připouštějícím hodnotu null ({0} je typ hodnoty, který nepřipouští hodnotu null).</target> <note /> </trans-unit> <trans-unit id="WRN_LowercaseEllSuffix"> <source>The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity</source> <target state="translated">Přípona l je snadno zaměnitelná s číslicí 1. V zájmu větší srozumitelnosti použijte písmeno L.</target> <note /> </trans-unit> <trans-unit id="WRN_LowercaseEllSuffix_Title"> <source>The 'l' suffix is easily confused with the digit '1'</source> <target state="translated">Přípona l je snadno zaměnitelná s číslicí 1.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEventUsageNoField"> <source>The event '{0}' can only appear on the left hand side of += or -=</source> <target state="translated">Událost {0} se může zobrazovat jenom na levé straně výrazu += nebo -=.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintOnlyAllowedOnGenericDecl"> <source>Constraints are not allowed on non-generic declarations</source> <target state="translated">U neobecných deklarací nejsou povolená omezení.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeParamMustBeIdentifier"> <source>Type parameter declaration must be an identifier not a type</source> <target state="translated">Deklarace parametru typů musí být identifikátor, ne typ.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberReserved"> <source>Type '{1}' already reserves a member called '{0}' with the same parameter types</source> <target state="translated">Typ {1} už rezervuje člen s názvem {0} se stejnými typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateParamName"> <source>The parameter name '{0}' is a duplicate</source> <target state="translated">Název parametru {0} je duplicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNameInNS"> <source>The namespace '{1}' already contains a definition for '{0}'</source> <target state="translated">Obor názvů {1} už obsahuje definici pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNameInClass"> <source>The type '{0}' already contains a definition for '{1}'</source> <target state="translated">Typ {0} už obsahuje definici pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotInContext"> <source>The name '{0}' does not exist in the current context</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje.</target> <note /> </trans-unit> <trans-unit id="ERR_NameNotInContextPossibleMissingReference"> <source>The name '{0}' does not exist in the current context (are you missing a reference to assembly '{1}'?)</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje. (Nechybí odkaz na sestavení {1}?)</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigContext"> <source>'{0}' is an ambiguous reference between '{1}' and '{2}'</source> <target state="translated">{0} je nejednoznačný odkaz mezi {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateUsing"> <source>The using directive for '{0}' appeared previously in this namespace</source> <target state="translated">Direktiva using pro {0} se objevila už dřív v tomto oboru názvů.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateUsing_Title"> <source>Using directive appeared previously in this namespace</source> <target state="translated">Direktiva Using se už v tomto oboru názvů objevila dříve.</target> <note /> </trans-unit> <trans-unit id="ERR_BadMemberFlag"> <source>The modifier '{0}' is not valid for this item</source> <target state="translated">Modifikátor {0} není pro tuto položku platný.</target> <note /> </trans-unit> <trans-unit id="ERR_BadMemberProtection"> <source>More than one protection modifier</source> <target state="translated">Víc než jeden modifikátor ochrany</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired"> <source>'{0}' hides inherited member '{1}'. Use the new keyword if hiding was intended.</source> <target state="translated">{0} skryje zděděný člen {1}. Pokud je skrytí úmyslné, použijte klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired_Title"> <source>Member hides inherited member; missing new keyword</source> <target state="translated">Člen skrývá zděděný člen. Chybí klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewRequired_Description"> <source>A variable was declared with the same name as a variable in a base type. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration.</source> <target state="translated">Proměnná se deklarovala se stejným názvem jako proměnná v základním typu. Klíčové slovo new se ale nepoužilo. Toto varování vás informuje, že byste měli použít new; proměnná je deklarovaná, jako by se v deklaraci používalo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewNotRequired"> <source>The member '{0}' does not hide an accessible member. The new keyword is not required.</source> <target state="translated">Člen {0} neskrývá přístupný člen. Klíčové slovo new se nevyžaduje.</target> <note /> </trans-unit> <trans-unit id="WRN_NewNotRequired_Title"> <source>Member does not hide an inherited member; new keyword is not required</source> <target state="translated">Člen neskrývá zděděný člen. Klíčové slovo new se nevyžaduje.</target> <note /> </trans-unit> <trans-unit id="ERR_CircConstValue"> <source>The evaluation of the constant value for '{0}' involves a circular definition</source> <target state="translated">Vyhodnocení konstantní hodnoty pro {0} zahrnuje cyklickou definici.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberAlreadyExists"> <source>Type '{1}' already defines a member called '{0}' with the same parameter types</source> <target state="translated">Typ {1} už definuje člen s názvem {0} se stejnými typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticNotVirtual"> <source>A static member cannot be marked as '{0}'</source> <target state="needs-review-translation">Statický člen {0} nemůže být označený klíčovými slovy override, virtual nebo abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotNew"> <source>A member '{0}' marked as override cannot be marked as new or virtual</source> <target state="translated">Člen {0} označený jako override nejde označit jako new nebo virtual.</target> <note /> </trans-unit> <trans-unit id="WRN_NewOrOverrideExpected"> <source>'{0}' hides inherited member '{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.</source> <target state="translated">'Člen {0} skryje zděděný člen {1}. Pokud má aktuální člen tuto implementaci přepsat, přidejte klíčové slovo override. Jinak přidejte klíčové slovo new.</target> <note /> </trans-unit> <trans-unit id="WRN_NewOrOverrideExpected_Title"> <source>Member hides inherited member; missing override keyword</source> <target state="translated">Člen skrývá zděděný člen. Chybí klíčové slovo override.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideNotExpected"> <source>'{0}': no suitable method found to override</source> <target state="translated">{0}: Nenašla se vhodná metoda k přepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceUnexpected"> <source>A namespace cannot directly contain members such as fields, methods or statements</source> <target state="needs-review-translation">Obor názvů nemůže přímo obsahovat členy, jako jsou pole a metody.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMember"> <source>'{0}' does not contain a definition for '{1}'</source> <target state="translated">{0} neobsahuje definici pro {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSKknown"> <source>'{0}' is a {1} but is used like a {2}</source> <target state="translated">{0} je {1}, ale používá se jako {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSKunknown"> <source>'{0}' is a {1}, which is not valid in the given context</source> <target state="translated">{0} je {1}, což není platné v daném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectRequired"> <source>An object reference is required for the non-static field, method, or property '{0}'</source> <target state="translated">Pro nestatické pole, metodu nebo vlastnost {0} se vyžaduje odkaz na objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigCall"> <source>The call is ambiguous between the following methods or properties: '{0}' and '{1}'</source> <target state="translated">Volání je nejednoznačné mezi následujícími metodami nebo vlastnostmi: {0} a {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAccess"> <source>'{0}' is inaccessible due to its protection level</source> <target state="translated">'Typ {0} je vzhledem k úrovni ochrany nepřístupný.</target> <note /> </trans-unit> <trans-unit id="ERR_MethDelegateMismatch"> <source>No overload for '{0}' matches delegate '{1}'</source> <target state="translated">Žádná přetížená metoda {0} neodpovídá delegátovi {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RetObjectRequired"> <source>An object of a type convertible to '{0}' is required</source> <target state="translated">Vyžaduje se objekt typu, který se dá převést na {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RetNoObjectRequired"> <source>Since '{0}' returns void, a return keyword must not be followed by an object expression</source> <target state="translated">Protože {0} vrací void, nesmí za klíčovým slovem return následovat výraz objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalDuplicate"> <source>A local variable or function named '{0}' is already defined in this scope</source> <target state="translated">Lokální proměnná nebo funkce s názvem {0} je už v tomto oboru definovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgLvalueExpected"> <source>The left-hand side of an assignment must be a variable, property or indexer</source> <target state="translated">Levou stranou přiřazení musí být proměnná, vlastnost nebo indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstParam"> <source>'{0}': a static constructor must be parameterless</source> <target state="translated">{0}: Statický konstruktor musí být bez parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_NotConstantExpression"> <source>The expression being assigned to '{0}' must be constant</source> <target state="translated">Výraz přiřazovaný proměnné {0} musí být konstantou.</target> <note /> </trans-unit> <trans-unit id="ERR_NotNullConstRefField"> <source>'{0}' is of type '{1}'. A const field of a reference type other than string can only be initialized with null.</source> <target state="translated">{0} je typu {1}. Pole const s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalIllegallyOverrides"> <source>A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter</source> <target state="translated">Místní proměnná nebo parametr s názvem {0} se nedá deklarovat v tomto oboru, protože se tento název používá v uzavírajícím místním oboru pro definování místní proměnné nebo parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUsingNamespace"> <source>A 'using namespace' directive can only be applied to namespaces; '{0}' is a type not a namespace. Consider a 'using static' directive instead</source> <target state="translated">Direktivu using namespace jde uplatnit jenom u oborů názvů; {0} je typ, ne obor názvů. Zkuste radši použít direktivu using static.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUsingType"> <source>A 'using static' directive can only be applied to types; '{0}' is a namespace not a type. Consider a 'using namespace' directive instead</source> <target state="translated">Direktiva using static se dá použít jenom u typů; {0} je obor názvů, ne typ. Zkuste radši použít direktivu using namespace.</target> <note /> </trans-unit> <trans-unit id="ERR_NoAliasHere"> <source>A 'using static' directive cannot be used to declare an alias</source> <target state="translated">Direktiva using static se nedá použít k deklarování aliasu.</target> <note /> </trans-unit> <trans-unit id="ERR_NoBreakOrCont"> <source>No enclosing loop out of which to break or continue</source> <target state="translated">Příkazy break a continue nejsou uvedené ve smyčce.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateLabel"> <source>The label '{0}' is a duplicate</source> <target state="translated">Návěstí {0} je duplicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConstructors"> <source>The type '{0}' has no constructors defined</source> <target state="translated">Pro typ {0} nejsou definované žádné konstruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNewAbstract"> <source>Cannot create an instance of the abstract type or interface '{0}'</source> <target state="translated">Nejde vytvořit instanci abstraktního typu nebo rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstValueRequired"> <source>A const field requires a value to be provided</source> <target state="translated">Pole const vyžaduje zadání hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_CircularBase"> <source>Circular base type dependency involving '{0}' and '{1}'</source> <target state="translated">Prvky {0} a {1} jsou součástí cyklické závislosti základního typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateConstructor"> <source>The delegate '{0}' does not have a valid constructor</source> <target state="translated">Delegát {0} nemá platný konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodNameExpected"> <source>Method name expected</source> <target state="translated">Očekává se název metody.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantExpected"> <source>A constant value is expected</source> <target state="translated">Očekává se konstantní hodnota.</target> <note /> </trans-unit> <trans-unit id="ERR_V6SwitchGoverningTypeValueExpected"> <source>A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type in C# 6 and earlier.</source> <target state="translated">Výraz switch nebo popisek větve musí být bool, char, string, integral, enum nebo odpovídající typ s možnou hodnotou null v jazyce C# 6 nebo starším.</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralTypeValueExpected"> <source>A value of an integral type expected</source> <target state="translated">Očekává se hodnota integrálního typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateCaseLabel"> <source>The switch statement contains multiple cases with the label value '{0}'</source> <target state="translated">Příkaz switch obsahuje víc případů s hodnotou návěstí {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidGotoCase"> <source>A goto case is only valid inside a switch statement</source> <target state="translated">Příkaz goto case je platný jenom uvnitř příkazu switch.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyLacksGet"> <source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože neobsahuje přistupující objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExceptionType"> <source>The type caught or thrown must be derived from System.Exception</source> <target state="translated">Zachycený nebo vyvolaný typ musí být odvozený od třídy System.Exception.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyThrow"> <source>A throw statement with no arguments is not allowed outside of a catch clause</source> <target state="translated">Příkaz throw bez argumentů není povolený vně klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFinallyLeave"> <source>Control cannot leave the body of a finally clause</source> <target state="translated">Řízení nemůže opustit tělo klauzule finally.</target> <note /> </trans-unit> <trans-unit id="ERR_LabelShadow"> <source>The label '{0}' shadows another label by the same name in a contained scope</source> <target state="translated">Návěstí {0} stíní v obsaženém oboru jiné návěstí se stejným názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_LabelNotFound"> <source>No such label '{0}' within the scope of the goto statement</source> <target state="translated">V rozsahu příkazu goto není žádné takové návěstí {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnreachableCatch"> <source>A previous catch clause already catches all exceptions of this or of a super type ('{0}')</source> <target state="translated">Předchozí klauzule catch už zachytává všechny výjimky vyvolávané tímto typem nebo nadtypem ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantTrue"> <source>Filter expression is a constant 'true', consider removing the filter</source> <target state="translated">Výraz filtru je konstantní hodnota true. Zvažte odebrání filtru.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantTrue_Title"> <source>Filter expression is a constant 'true'</source> <target state="translated">Výraz filtru je konstantní hodnota true.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnExpected"> <source>'{0}': not all code paths return a value</source> <target state="translated">{0}: Ne všechny cesty kódu vrací hodnotu.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableCode_Title"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchFallThrough"> <source>Control cannot fall through from one case label ('{0}') to another</source> <target state="translated">Řízení se nedá předat z jednoho návěstí příkazu case ({0}) do jiného.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLabel"> <source>This label has not been referenced</source> <target state="translated">Na tuto jmenovku se neodkazuje.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLabel_Title"> <source>This label has not been referenced</source> <target state="translated">Na tuto jmenovku se neodkazuje.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolation"> <source>Use of unassigned local variable '{0}'</source> <target state="translated">Použila se nepřiřazená lokální proměnná {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVar"> <source>The variable '{0}' is declared but never used</source> <target state="translated">Proměnná {0} je deklarovaná, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVar_Title"> <source>Variable is declared but never used</source> <target state="translated">Proměnná je deklarovaná, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedField"> <source>The field '{0}' is never used</source> <target state="translated">Pole {0} se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedField_Title"> <source>Field is never used</source> <target state="translated">Pole se nikdy nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationField"> <source>Use of possibly unassigned field '{0}'</source> <target state="translated">Použila se možná nepřiřazené pole {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationProperty"> <source>Use of possibly unassigned auto-implemented property '{0}'</source> <target state="translated">Použití pravděpodobně nepřiřazené automaticky implementované vlastnosti {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnassignedThis"> <source>Field '{0}' must be fully assigned before control is returned to the caller</source> <target state="translated">Před předáním řízení volající proceduře musí být pole {0} plně přiřazené.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigQM"> <source>Type of conditional expression cannot be determined because '{0}' and '{1}' implicitly convert to one another</source> <target state="translated">Typ podmíněného výrazu nejde určit, protože {0} a {1} se implicitně převádějí jeden na druhého.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidQM"> <source>Type of conditional expression cannot be determined because there is no implicit conversion between '{0}' and '{1}'</source> <target state="translated">Nejde zjistit typ podmíněného výrazu, protože mezi typy {0} a {1} nedochází k implicitnímu převodu</target> <note /> </trans-unit> <trans-unit id="ERR_NoBaseClass"> <source>A base class is required for a 'base' reference</source> <target state="translated">Pro odkaz base se vyžaduje základní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseIllegal"> <source>Use of keyword 'base' is not valid in this context</source> <target state="translated">Použití klíčového slova base není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectProhibited"> <source>Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead</source> <target state="translated">K členovi {0} nejde přistupovat pomocí odkazu na instanci. Namísto toho použijte kvalifikaci pomocí názvu typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamUnassigned"> <source>The out parameter '{0}' must be assigned to before control leaves the current method</source> <target state="translated">Parametr out {0} se musí přiřadit ještě předtím, než aktuální metoda předá řízení.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidArray"> <source>Invalid rank specifier: expected ',' or ']'</source> <target state="translated">Specifikátor rozsahu je neplatný. Očekávala se čárka (,) nebo pravá hranatá závorka ].</target> <note /> </trans-unit> <trans-unit id="ERR_ExternHasBody"> <source>'{0}' cannot be extern and declare a body</source> <target state="translated">{0} nemůže být extern a deklarovat tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternHasConstructorInitializer"> <source>'{0}' cannot be extern and have a constructor initializer</source> <target state="translated">{0} nemůže být extern a mít inicializátor konstruktoru.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAndExtern"> <source>'{0}' cannot be both extern and abstract</source> <target state="translated">{0} nemůže být extern i abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeParamType"> <source>Attribute constructor parameter '{0}' has type '{1}', which is not a valid attribute parameter type</source> <target state="translated">Parametr {0} konstruktoru atributu má typ {1}, což není platný typ pro parametr atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeArgument"> <source>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type</source> <target state="translated">Argumentem atributu musí být konstantní výraz, výraz typeof nebo výraz vytvoření pole s typem parametru atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAttributeParamDefaultArgument"> <source>Attribute constructor parameter '{0}' is optional, but no default parameter value was specified.</source> <target state="translated">Parametr {0} konstruktoru atributu je nepovinný, ale nebyla zadaná žádná výchozí hodnota parametru.</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysTrue"> <source>The given expression is always of the provided ('{0}') type</source> <target state="translated">Tento výraz je vždy zadaného typu ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysTrue_Title"> <source>'is' expression's given expression is always of the provided type</source> <target state="translated">'Daný výraz is je vždycky zadaného typu.</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysFalse"> <source>The given expression is never of the provided ('{0}') type</source> <target state="translated">Tento výraz nikdy není zadaného typu ({0}).</target> <note /> </trans-unit> <trans-unit id="WRN_IsAlwaysFalse_Title"> <source>'is' expression's given expression is never of the provided type</source> <target state="translated">'Daný výraz is není nikdy zadaného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_LockNeedsReference"> <source>'{0}' is not a reference type as required by the lock statement</source> <target state="translated">{0} není typu odkaz, jak vyžaduje příkaz lock</target> <note /> </trans-unit> <trans-unit id="ERR_NullNotValid"> <source>Use of null is not valid in this context</source> <target state="translated">Použití hodnoty NULL není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultLiteralNotValid"> <source>Use of default literal is not valid in this context</source> <target state="translated">Použití výchozího literálu není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationThis"> <source>The 'this' object cannot be used before all of its fields have been assigned</source> <target state="translated">Objekt this se nedá použít, dokud se nepřiřadí všechna jeho pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ArgsInvalid"> <source>The __arglist construct is valid only within a variable argument method</source> <target state="translated">Konstrukce __arglist je platná jenom v rámci metody s proměnnými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_PtrExpected"> <source>The * or -&gt; operator must be applied to a pointer</source> <target state="translated">Operátor * nebo -&gt; musí být použitý u ukazatele.</target> <note /> </trans-unit> <trans-unit id="ERR_PtrIndexSingle"> <source>A pointer must be indexed by only one value</source> <target state="translated">Ukazatel může být indexován jenom jednou hodnotou.</target> <note /> </trans-unit> <trans-unit id="WRN_ByRefNonAgileField"> <source>Using '{0}' as a ref or out value or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class</source> <target state="translated">Použití prvku {0} jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit výjimku při běhu, protože se jedná o pole třídy marshal-by-reference.</target> <note /> </trans-unit> <trans-unit id="WRN_ByRefNonAgileField_Title"> <source>Using a field of a marshal-by-reference class as a ref or out value or taking its address may cause a runtime exception</source> <target state="translated">Použití pole třídy marshal-by-reference jako hodnoty Ref nebo Out nebo převzetí jeho adresy může způsobit běhovou výjimku.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyStatic"> <source>A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)</source> <target state="translated">Do statického pole určeného jen pro čtení nejde přiřazovat (kromě případu, kdy se nachází uvnitř statického konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyStatic"> <source>A static readonly field cannot be used as a ref or out value (except in a static constructor)</source> <target state="translated">Statické pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř statického konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyProp"> <source>Property or indexer '{0}' cannot be assigned to -- it is read only</source> <target state="translated">Vlastnost nebo indexer {0} nejde přiřadit – je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalStatement"> <source>Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement</source> <target state="translated">Jako příkaz jde použít jenom objektové výrazy přiřazení, volání, zvýšení nebo snížení hodnoty nebo výrazy obsahující operátor new.</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetEnumerator"> <source>foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNext' method and public 'Current' property</source> <target state="translated">Příkaz foreach vyžaduje, aby typ vracených hodnot {0} pro {1} měl vhodnou veřejnou metodu MoveNext a veřejnou vlastnost Current.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyLocals"> <source>Only 65534 locals, including those generated by the compiler, are allowed</source> <target state="translated">Je povolených jenom 65 534 lokálních proměnných, včetně těch, které generuje kompilátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractBaseCall"> <source>Cannot call an abstract base member: '{0}'</source> <target state="translated">Nejde volat abstraktní základní člen: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefProperty"> <source>A property or indexer may not be passed as an out or ref parameter</source> <target state="translated">Vlastnost nebo indexer nejde předat jako parametr ref nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_ManagedAddr"> <source>Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')</source> <target state="translated">Nejde převzít adresu proměnné spravovaného typu ({0}), získat její velikost nebo deklarovat ukazatel na ni.</target> <note /> </trans-unit> <trans-unit id="ERR_BadFixedInitType"> <source>The type of a local declared in a fixed statement must be a pointer type</source> <target state="translated">Lokální proměnná deklarovaná v příkazu fixed musí být typu ukazatel.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedMustInit"> <source>You must provide an initializer in a fixed or using statement declaration</source> <target state="translated">V deklaracích příkazů fixed a using je nutné zadat inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAddrOp"> <source>Cannot take the address of the given expression</source> <target state="translated">Nejde převzít adresu daného výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNeeded"> <source>You can only take the address of an unfixed expression inside of a fixed statement initializer</source> <target state="translated">Adresu volného výrazu jde převzít jenom uvnitř inicializátoru příkazu fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNotNeeded"> <source>You cannot use the fixed statement to take the address of an already fixed expression</source> <target state="translated">K převzetí adresy výrazu, který je už nastavený jako pevný, nejde použít příkaz fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeNeeded"> <source>Pointers and fixed size buffers may only be used in an unsafe context</source> <target state="translated">Ukazatele a vyrovnávací paměti pevné velikosti jde použít jenom v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_OpTFRetType"> <source>The return type of operator True or False must be bool</source> <target state="translated">Vrácená hodnota operátorů True a False musí být typu bool.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorNeedsMatch"> <source>The operator '{0}' requires a matching operator '{1}' to also be defined</source> <target state="translated">Operátor {0} vyžaduje, aby byl definovaný i odpovídající operátor {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBoolOp"> <source>In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type and parameter types</source> <target state="translated">Pokud má být uživatelem definovaný logický operátor ({0}) použitelný jako operátor zkráceného vyhodnocení, musí vracet hodnotu stejného typu a mít stejné typy parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MustHaveOpTF"> <source>In order for '{0}' to be applicable as a short circuit operator, its declaring type '{1}' must define operator true and operator false</source> <target state="translated">Aby byl {0} použitelný jako operátor zkráceného vyhodnocení, musí jeho deklarující typ {1} definovat operátor true a operátor false.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVarAssg"> <source>The variable '{0}' is assigned but its value is never used</source> <target state="translated">Proměnná {0} má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedVarAssg_Title"> <source>Variable is assigned but its value is never used</source> <target state="translated">Proměnná má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_CheckedOverflow"> <source>The operation overflows at compile time in checked mode</source> <target state="translated">Během kompilace v režimu kontroly došlo k přetečení.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstOutOfRangeChecked"> <source>Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)</source> <target state="translated">Konstantní hodnotu {0} nejde převést na typ {1} (k přepsání jde použít syntaxi unchecked).</target> <note /> </trans-unit> <trans-unit id="ERR_BadVarargs"> <source>A method with vararg cannot be generic, be in a generic type, or have a params parameter</source> <target state="translated">Metoda s parametrem vararg nemůže být obecná, být obecného typu nebo mít pole parametr params.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsMustBeArray"> <source>The params parameter must be a single dimensional array</source> <target state="translated">Parametr params musí být jednorozměrné pole.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalArglist"> <source>An __arglist expression may only appear inside of a call or new expression</source> <target state="translated">Výraz __arglist může být jedině uvnitř volání nebo výrazu new.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalUnsafe"> <source>Unsafe code may only appear if compiling with /unsafe</source> <target state="translated">Nebezpečný kód může vzniknout jenom při kompilaci s přepínačem /unsafe.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigMember"> <source>Ambiguity between '{0}' and '{1}'</source> <target state="translated">Došlo k nejednoznačnosti mezi metodami nebo vlastnostmi {0} a {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadForeachDecl"> <source>Type and identifier are both required in a foreach statement</source> <target state="translated">V příkazu foreach se vyžaduje typ i identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsLast"> <source>A params parameter must be the last parameter in a formal parameter list</source> <target state="translated">Parametr params musí být posledním parametrem v seznamu formálních parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_SizeofUnsafe"> <source>'{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context</source> <target state="translated">{0} nemá předdefinovanou velikost. Operátor sizeof jde proto použít jenom v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInNS"> <source>The type or namespace name '{0}' does not exist in the namespace '{1}' (are you missing an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} neexistuje v oboru názvů {1}. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_FieldInitRefNonstatic"> <source>A field initializer cannot reference the non-static field, method, or property '{0}'</source> <target state="translated">Inicializátor pole nemůže odkazovat na nestatické pole, metodu nebo vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedNonOverride"> <source>'{0}' cannot be sealed because it is not an override</source> <target state="translated">{0} nejde zapečetit, protože to není přepis.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideSealed"> <source>'{0}': cannot override inherited member '{1}' because it is sealed</source> <target state="translated">{0}: Nejde přepsat zděděný člen {1}, protože je zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidError"> <source>The operation in question is undefined on void pointers</source> <target state="translated">Příslušná operace není definovaná pro ukazatele typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnOverride"> <source>The Conditional attribute is not valid on '{0}' because it is an override method</source> <target state="translated">Atribut Conditional není pro {0} platný, protože je to metoda override.</target> <note /> </trans-unit> <trans-unit id="ERR_PointerInAsOrIs"> <source>Neither 'is' nor 'as' is valid on pointer types</source> <target state="translated">Klíčová slova is a as nejsou platná pro ukazatele.</target> <note /> </trans-unit> <trans-unit id="ERR_CallingFinalizeDeprecated"> <source>Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.</source> <target state="translated">Destruktory a metodu object.Finalize nejde volat přímo. Zvažte možnost volání metody IDisposable.Dispose, pokud je k dispozici.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleTypeNameNotFound"> <source>The type or namespace name '{0}' could not be found (are you missing a using directive or an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} se nenašel. (Nechybí direktiva using nebo odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeStackAllocSize"> <source>Cannot use a negative size with stackalloc</source> <target state="translated">Ve výrazu stackalloc nejde použít zápornou velikost.</target> <note /> </trans-unit> <trans-unit id="ERR_NegativeArraySize"> <source>Cannot create an array with a negative size</source> <target state="translated">Nejde vytvořit pole se zápornou velikostí.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideFinalizeDeprecated"> <source>Do not override object.Finalize. Instead, provide a destructor.</source> <target state="translated">Nepřepisujte metodu object.Finalize. Raději použijte destruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_CallingBaseFinalizeDeprecated"> <source>Do not directly call your base type Finalize method. It is called automatically from your destructor.</source> <target state="translated">Nevolejte přímo metodu Finalize základního typu. Tuto metodu volá automaticky destruktor.</target> <note /> </trans-unit> <trans-unit id="WRN_NegativeArrayIndex"> <source>Indexing an array with a negative index (array indices always start at zero)</source> <target state="translated">Došlo k indexování pole záporným indexem (indexy polí vždy začínají hodnotou 0).</target> <note /> </trans-unit> <trans-unit id="WRN_NegativeArrayIndex_Title"> <source>Indexing an array with a negative index</source> <target state="translated">Došlo k indexování pole záporným indexem.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareLeft"> <source>Possible unintended reference comparison; to get a value comparison, cast the left hand side to type '{0}'</source> <target state="translated">Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte levou stranu na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareLeft_Title"> <source>Possible unintended reference comparison; left hand side needs cast</source> <target state="translated">Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat levou stranu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareRight"> <source>Possible unintended reference comparison; to get a value comparison, cast the right hand side to type '{0}'</source> <target state="translated">Možná došlo k neúmyslnému porovnání ukazatelů; chcete-li porovnat hodnoty, přetypujte pravou stranu na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRefCompareRight_Title"> <source>Possible unintended reference comparison; right hand side needs cast</source> <target state="translated">Pravděpodobně došlo k neúmyslnému porovnání odkazů. Je třeba přetypovat pravou stranu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCastInFixed"> <source>The right hand side of a fixed statement assignment may not be a cast expression</source> <target state="translated">Pravá strana přiřazení příkazu fixed nemůže být výrazem přetypování.</target> <note /> </trans-unit> <trans-unit id="ERR_StackallocInCatchFinally"> <source>stackalloc may not be used in a catch or finally block</source> <target state="translated">Výraz stackalloc nejde použít v bloku catch nebo finally.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsLast"> <source>An __arglist parameter must be the last parameter in a formal parameter list</source> <target state="translated">Parametr __arglist musí být posledním parametrem v seznamu formálních parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPartial"> <source>Missing partial modifier on declaration of type '{0}'; another partial declaration of this type exists</source> <target state="translated">Chybí částečný modifikátor deklarace typu {0}; existuje jiná částečná deklarace tohoto typu.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialTypeKindConflict"> <source>Partial declarations of '{0}' must be all classes, all record classes, all structs, all record structs, or all interfaces</source> <target state="needs-review-translation">Částečné deklarace {0} musí být jen třídy, jen záznamy, jen struktury, nebo jen rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialModifierConflict"> <source>Partial declarations of '{0}' have conflicting accessibility modifiers</source> <target state="translated">Částečné deklarace {0} mají konfliktní modifikátory dostupnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMultipleBases"> <source>Partial declarations of '{0}' must not specify different base classes</source> <target state="translated">Částečné deklarace {0} nesmí určovat různé základní třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongTypeParams"> <source>Partial declarations of '{0}' must have the same type parameter names in the same order</source> <target state="translated">Částečné deklarace {0} musí mít stejné názvy parametrů typů ve stejném pořadí.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongConstraints"> <source>Partial declarations of '{0}' have inconsistent constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace {0} mají nekonzistentní omezení parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoImplicitConvCast"> <source>Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)</source> <target state="translated">Typ {0} nejde implicitně převést na typ {1}. Existuje explicitní převod. (Nechybí výraz přetypování?)</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMisplaced"> <source>The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.</source> <target state="translated">Modifikátor partial se může objevit jen bezprostředně před klíčovými slovy class, record, struct, interface nebo návratovým typem metody.</target> <note /> </trans-unit> <trans-unit id="ERR_ImportedCircularBase"> <source>Imported type '{0}' is invalid. It contains a circular base type dependency.</source> <target state="translated">Importovaný typ {0} je neplatný. Obsahuje cyklickou závislost základních typů.</target> <note /> </trans-unit> <trans-unit id="ERR_UseDefViolationOut"> <source>Use of unassigned out parameter '{0}'</source> <target state="translated">Použil se nepřiřazený parametr out {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ArraySizeInDeclaration"> <source>Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)</source> <target state="translated">Velikost pole nejde určit v deklaraci proměnné (zkuste inicializaci pomocí výrazu new).</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleGetter"> <source>The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt get není dostupný.</target> <note /> </trans-unit> <trans-unit id="ERR_InaccessibleSetter"> <source>The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible</source> <target state="translated">Vlastnost nebo indexer {0} nejde v tomto kontextu použít, protože přistupující objekt jet není dostupný.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPropertyAccessMod"> <source>The accessibility modifier of the '{0}' accessor must be more restrictive than the property or indexer '{1}'</source> <target state="translated">Modifikátor dostupnosti přistupujícího objektu {0} musí být více omezující než vlastnost nebo indexer {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicatePropertyAccessMods"> <source>Cannot specify accessibility modifiers for both accessors of the property or indexer '{0}'</source> <target state="translated">Nejde zadat modifikátory dostupnosti pro přistupující objekty jak vlastnosti, tak i indexer {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AccessModMissingAccessor"> <source>'{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor</source> <target state="translated">{0}: Modifikátory přístupnosti u přistupujících objektů se můžou používat, jenom pokud vlastnost nebo indexeru má přistupující objekt get i set.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedInterfaceAccessor"> <source>'{0}' does not implement interface member '{1}'. '{2}' is not public.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} není veřejný.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternIsAmbiguous"> <source>'{0}' does not implement the '{1}' pattern. '{2}' is ambiguous with '{3}'.</source> <target state="translated">{0} neimplementuje vzorek {1}. {2} je nejednoznačný vzhledem k: {3}.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternIsAmbiguous_Title"> <source>Type does not implement the collection pattern; members are ambiguous</source> <target state="translated">Typ neimplementuje vzorek kolekce. Členové nejsou jednoznační.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternBadSignature"> <source>'{0}' does not implement the '{1}' pattern. '{2}' has the wrong signature.</source> <target state="translated">{0} neimplementuje vzorek {1}. {2} nemá správný podpis.</target> <note /> </trans-unit> <trans-unit id="WRN_PatternBadSignature_Title"> <source>Type does not implement the collection pattern; member has the wrong signature</source> <target state="translated">Typ neimplementuje vzorek kolekce. Člen nemá správný podpis.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefNotEqualToThis"> <source>Friend access was granted by '{0}', but the public key of the output assembly ('{1}') does not match that specified by the InternalsVisibleTo attribute in the granting assembly.</source> <target state="translated">Sestavení {0} udělilo přístup typu Friend, ale veřejný klíč výstupního sestavení ({1}) neodpovídá klíči určenému atributem InternalsVisibleTo v udělujícím sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendRefSigningMismatch"> <source>Friend access was granted by '{0}', but the strong name signing state of the output assembly does not match that of the granting assembly.</source> <target state="translated">Sestavení {0} udělilo přístup typu Friend, ale stav podepsání silného názvu u výstupního sestavení neodpovídá stavu udělujícího sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_SequentialOnPartialClass"> <source>There is no defined ordering between fields in multiple declarations of partial struct '{0}'. To specify an ordering, all instance fields must be in the same declaration.</source> <target state="translated">Mezi poli více deklarací částečné třídy nebo struktury {0} není žádné definované řazení. Pokud chcete zadat řazení, musí být všechna pole instancí ve stejné deklaraci.</target> <note /> </trans-unit> <trans-unit id="WRN_SequentialOnPartialClass_Title"> <source>There is no defined ordering between fields in multiple declarations of partial struct</source> <target state="translated">Není nadefinované řazení mezi poli ve více deklaracích částečné struktury.</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstType"> <source>The type '{0}' cannot be declared const</source> <target state="translated">Typ {0} nemůže být deklarovaný jako const.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNewTyvar"> <source>Cannot create an instance of the variable type '{0}' because it does not have the new() constraint</source> <target state="translated">Nejde vytvořit instanci proměnné typu {0}, protože nemá omezení new().</target> <note /> </trans-unit> <trans-unit id="ERR_BadArity"> <source>Using the generic {1} '{0}' requires {2} type arguments</source> <target state="translated">Použití obecného prvku {1} {0} vyžaduje tento počet argumentů typů: {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeArgument"> <source>The type '{0}' may not be used as a type argument</source> <target state="translated">Typ {0} nejde použít jako argument typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeArgsNotAllowed"> <source>The {1} '{0}' cannot be used with type arguments</source> <target state="translated">{1} {0} nejde použít s argumenty typů.</target> <note /> </trans-unit> <trans-unit id="ERR_HasNoTypeVars"> <source>The non-generic {1} '{0}' cannot be used with type arguments</source> <target state="translated">Neobecnou možnost {1} {0} nejde použít s argumenty typů.</target> <note /> </trans-unit> <trans-unit id="ERR_NewConstraintNotSatisfied"> <source>'{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">'Objekt {2} musí být neabstraktního typu s veřejným konstruktorem bez parametrů, jinak jej nejde použít jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedRefType"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný implicitní převod odkazu z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedNullableEnum"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedNullableInterface"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Typ {3} s možnou hodnotou null nevyhovuje omezení {1}. Typy s možnou hodnotou null nemůžou vyhovět žádným omezením rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedTyVar"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení ani převod typu parametru z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericConstraintNotSatisfiedValType"> <source>The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.</source> <target state="translated">Typ {3} nejde použít jako parametr typu {2} v obecném typu nebo metodě {0}. Neexistuje žádný převod na uzavřené určení z {3} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateGeneratedName"> <source>The parameter name '{0}' conflicts with an automatically-generated parameter name</source> <target state="translated">Název parametru {0} je v konfliktu s automaticky generovaným názvem parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalSingleTypeNameNotFound"> <source>The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?)</source> <target state="translated">Typ nebo název oboru názvů {0} se nenašel v globálním oboru názvů. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundMustBeLast"> <source>The new() constraint must be the last constraint specified</source> <target state="translated">Omezení new() musí být poslední zadané omezení.</target> <note /> </trans-unit> <trans-unit id="WRN_MainCantBeGeneric"> <source>'{0}': an entry point cannot be generic or in a generic type</source> <target state="translated">{0}: Vstupní bod nemůže být obecný nebo v obecném typu.</target> <note /> </trans-unit> <trans-unit id="WRN_MainCantBeGeneric_Title"> <source>An entry point cannot be generic or in a generic type</source> <target state="translated">Vstupní bod nemůže být obecný nebo v obecném typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarCantBeNull"> <source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source> <target state="translated">Hodnotu Null nejde převést na parametr typu {0}, protože by se mohlo jednat o typ, který nemůže mít hodnotu null. Zvažte možnost použití výrazu default({0}).</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateBound"> <source>Duplicate constraint '{0}' for type parameter '{1}'</source> <target state="translated">Duplicitní omezení {0} pro parametru typu {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ClassBoundNotFirst"> <source>The class type constraint '{0}' must come before any other constraints</source> <target state="translated">Omezení typu třídy {0} musí předcházet všem dalším omezením.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRetType"> <source>'{1} {0}' has the wrong return type</source> <target state="translated">{1} {0} má nesprávný návratový typ.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateRefMismatch"> <source>Ref mismatch between '{0}' and delegate '{1}'</source> <target state="translated">Mezi {0} a delegátem {1} se neshoduje odkaz.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConstraintClause"> <source>A constraint clause has already been specified for type parameter '{0}'. All of the constraints for a type parameter must be specified in a single where clause.</source> <target state="translated">Klauzule omezení už byla přidaná pro parametr typu {0}. Všechna omezení pro parametr typu musí být zadaná v jediné klauzuli where.</target> <note /> </trans-unit> <trans-unit id="ERR_CantInferMethTypeArgs"> <source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source> <target state="translated">Argumenty typu pro metodu {0} nejde stanovit z použití. Zadejte argumenty typu explicitně.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalSameNameAsTypeParam"> <source>'{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter</source> <target state="translated">{0}: Parametr, místní proměnná nebo místní funkce nemůžou mít stejný název jako parametr typů metod.</target> <note /> </trans-unit> <trans-unit id="ERR_AsWithTypeVar"> <source>The type parameter '{0}' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint</source> <target state="translated">Parametr typu {0} nejde používat s operátorem as, protože nemá omezení typu třída ani omezení class.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedFieldAssg"> <source>The field '{0}' is assigned but its value is never used</source> <target state="translated">Pole {0} má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedFieldAssg_Title"> <source>Field is assigned but its value is never used</source> <target state="translated">Pole má přiřazenou hodnotu, ale nikdy se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIndexerNameAttr"> <source>The '{0}' attribute is valid only on an indexer that is not an explicit interface member declaration</source> <target state="translated">Atribut {0} je platný jenom pro indexer, který nepředstavuje explicitní deklaraci člena rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AttrArgWithTypeVars"> <source>'{0}': an attribute argument cannot use type parameters</source> <target state="translated">{0}: Argument atributu nemůže používat parametry typů.</target> <note /> </trans-unit> <trans-unit id="ERR_NewTyvarWithArgs"> <source>'{0}': cannot provide arguments when creating an instance of a variable type</source> <target state="translated">{0}: Při vytváření instance typu proměnné nejde zadat argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractSealedStatic"> <source>'{0}': an abstract type cannot be sealed or static</source> <target state="translated">{0}: Abstraktní typ nemůže být sealed ani static.</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousXMLReference"> <source>Ambiguous reference in cref attribute: '{0}'. Assuming '{1}', but could have also matched other overloads including '{2}'.</source> <target state="translated">Nejednoznačný odkaz v atributu cref: {0}. Předpokládá se {1}, ale mohla se najít shoda s dalšími přetíženími, včetně {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_AmbiguousXMLReference_Title"> <source>Ambiguous reference in cref attribute</source> <target state="translated">Nejednoznačný odkaz v atributu cref</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef"> <source>'{0}': a reference to a volatile field will not be treated as volatile</source> <target state="translated">{0}: Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef_Title"> <source>A reference to a volatile field will not be treated as volatile</source> <target state="translated">Odkaz na pole s modifikátorem volatile se nezpracuje jako volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_VolatileByRef_Description"> <source>A volatile field should not normally be used as a ref or out value, since it will not be treated as volatile. There are exceptions to this, such as when calling an interlocked API.</source> <target state="translated">Pole s modifikátorem volatile by se normálně mělo používat jako hodnota Ref nebo Out, protože se s ním nebude zacházet jako s nestálým. Pro toto pravidlo platí výjimky, například při volání propojeného API.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithImpl"> <source>Since '{1}' has the ComImport attribute, '{0}' must be extern or abstract</source> <target state="translated">Protože {1} má atribut ComImport, {0} musí být externí nebo abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithBase"> <source>'{0}': a class with the ComImport attribute cannot specify a base class</source> <target state="translated">{0}: Třída s atributem ComImport nemůže určovat základní třídu.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplBadConstraints"> <source>The constraints for type parameter '{0}' of method '{1}' must match the constraints for type parameter '{2}' of interface method '{3}'. Consider using an explicit interface implementation instead.</source> <target state="translated">Omezení pro parametr typu {0} metody {1} se musí shodovat s omezeními u parametru typu {2} metody rozhraní {3}. Místo toho zvažte použití explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplBadTupleNames"> <source>The tuple element names in the signature of method '{0}' must match the tuple element names of interface method '{1}' (including on the return type).</source> <target state="translated">Názvy prvků řazené kolekce členů v signatuře metody {0} se musí shodovat s názvy prvků řazené kolekce členů metody rozhraní {1} (a zároveň u návratového typu).</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInAgg"> <source>The type name '{0}' does not exist in the type '{1}'</source> <target state="translated">Název typu {0} neexistuje v typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MethGrpToNonDel"> <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source> <target state="translated">Nejde převést skupinu metod {0} na nedelegující typ {1}. Chtěli jste volat tuto metodu?</target> <note /> </trans-unit> <trans-unit id="ERR_BadExternAlias"> <source>The extern alias '{0}' was not specified in a /reference option</source> <target state="translated">Externí alias {0} nebyl zadaný jako možnost /reference.</target> <note /> </trans-unit> <trans-unit id="ERR_ColColWithTypeAlias"> <source>Cannot use alias '{0}' with '::' since the alias references a type. Use '.' instead.</source> <target state="translated">Zápis aliasu {0} se dvěma dvojtečkami (::) nejde použít, protože alias odkazuje na typ. Místo toho použijte zápis s tečkou (.).</target> <note /> </trans-unit> <trans-unit id="ERR_AliasNotFound"> <source>Alias '{0}' not found</source> <target state="translated">Alias {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameAggAgg"> <source>The type '{1}' exists in both '{0}' and '{2}'</source> <target state="translated">Typ {1} existuje v {0} i {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameNsAgg"> <source>The namespace '{1}' in '{0}' conflicts with the type '{3}' in '{2}'</source> <target state="translated">Obor názvů {1} v {0} je v konfliktu s typem {3} v {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisNsAgg"> <source>The namespace '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the namespace defined in '{0}'.</source> <target state="translated">Obor názvů {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se obor názvů definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisNsAgg_Title"> <source>Namespace conflicts with imported type</source> <target state="translated">Obor názvů je v konfliktu s importovaným typem.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggAgg"> <source>The type '{1}' in '{0}' conflicts with the imported type '{3}' in '{2}'. Using the type defined in '{0}'.</source> <target state="translated">Typ {1} v {0} je v konfliktu s importovaným typem {3} v {2}. Použije se typ definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggAgg_Title"> <source>Type conflicts with imported type</source> <target state="translated">Typ je v konfliktu s importovaným typem.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggNs"> <source>The type '{1}' in '{0}' conflicts with the imported namespace '{3}' in '{2}'. Using the type defined in '{0}'.</source> <target state="translated">Typ {1} v {0} je v konfliktu s importovaným oborem názvů {3} v {2}. Použije se typ definovaný v {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_SameFullNameThisAggNs_Title"> <source>Type conflicts with imported namespace</source> <target state="translated">Typ je v konfliktu s importovaným oborem názvů.</target> <note /> </trans-unit> <trans-unit id="ERR_SameFullNameThisAggThisNs"> <source>The type '{1}' in '{0}' conflicts with the namespace '{3}' in '{2}'</source> <target state="translated">Typ {1} v {0} je v konfliktu s oborem názvů {3} v {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternAfterElements"> <source>An extern alias declaration must precede all other elements defined in the namespace</source> <target state="translated">Deklarace externího aliasu musí předcházet všem ostatním prvkům definovaným v oboru názvů.</target> <note /> </trans-unit> <trans-unit id="WRN_GlobalAliasDefn"> <source>Defining an alias named 'global' is ill-advised since 'global::' always references the global namespace and not an alias</source> <target state="translated">Definování aliasu s názvem global se nedoporučuje, protože global:: vždycky odkazuje na globální obor názvů, ne na alias.</target> <note /> </trans-unit> <trans-unit id="WRN_GlobalAliasDefn_Title"> <source>Defining an alias named 'global' is ill-advised</source> <target state="translated">Definování aliasu s názvem global se nedoporučuje.</target> <note /> </trans-unit> <trans-unit id="ERR_SealedStaticClass"> <source>'{0}': a type cannot be both static and sealed</source> <target state="translated">{0}: Typ nemůže být zároveň statický i zapečetěný.</target> <note /> </trans-unit> <trans-unit id="ERR_PrivateAbstractAccessor"> <source>'{0}': abstract properties cannot have private accessors</source> <target state="translated">{0}: Abstraktní vlastnosti nemůžou mít privátní přistupující objekty.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueExpected"> <source>Syntax error; value expected</source> <target state="translated">Chyba syntaxe: Očekávala se hodnota.</target> <note /> </trans-unit> <trans-unit id="ERR_UnboxNotLValue"> <source>Cannot modify the result of an unboxing conversion</source> <target state="translated">Nejde změnit výsledek unboxingového převodu.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonMethGrpInForEach"> <source>Foreach cannot operate on a '{0}'. Did you intend to invoke the '{0}'?</source> <target state="translated">Příkaz foreach nejde použít pro {0}. Měli jste v úmyslu vyvolat {0}?</target> <note /> </trans-unit> <trans-unit id="ERR_BadIncDecRetType"> <source>The return type for ++ or -- operator must match the parameter type or be derived from the parameter type</source> <target state="translated">Typ vrácené hodnoty operátorů ++ a -- musí odpovídat danému typu parametru nebo z něho musí být odvozený.</target> <note /> </trans-unit> <trans-unit id="ERR_RefValBoundWithClass"> <source>'{0}': cannot specify both a constraint class and the 'class' or 'struct' constraint</source> <target state="translated">{0}: Nejde zadat třídu omezení a zároveň omezení class nebo struct.</target> <note /> </trans-unit> <trans-unit id="ERR_NewBoundWithVal"> <source>The 'new()' constraint cannot be used with the 'struct' constraint</source> <target state="translated">Omezení new() nejde používat s omezením struct.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConstraintNotSatisfied"> <source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ odkazu, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ValConstraintNotSatisfied"> <source>The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'</source> <target state="translated">Typ {2} musí být typ, který nemůže mít hodnotu null, aby ho bylo možné používat jako parametr {1} v obecném typu nebo metodě {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CircularConstraint"> <source>Circular constraint dependency involving '{0}' and '{1}'</source> <target state="translated">Cyklická závislost omezení zahrnující {0} a {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BaseConstraintConflict"> <source>Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'</source> <target state="translated">Parametr typu {0} dědí konfliktní omezení {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConWithValCon"> <source>Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'</source> <target state="translated">Parametr typu {1} má omezení struct, takže není možné používat {1} jako omezení pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigUDConv"> <source>Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'</source> <target state="translated">Při převodu typu {2} na typ {3} došlo k uživatelem definovaným nejednoznačným převodům typu {0} na typ {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_AlwaysNull"> <source>The result of the expression is always 'null' of type '{0}'</source> <target state="translated">Výsledek výrazu je vždy hodnota null typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_AlwaysNull_Title"> <source>The result of the expression is always 'null'</source> <target state="translated">Výsledek výrazu je vždycky null.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnThis"> <source>Cannot return 'this' by reference.</source> <target state="translated">Nejde vrátit this pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeCtorInParameter"> <source>Cannot use attribute constructor '{0}' because it has 'in' parameters.</source> <target state="translated">Nejde použít konstruktor atributu {0}, protože má parametry in.</target> <note /> </trans-unit> <trans-unit id="ERR_OverrideWithConstraints"> <source>Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint.</source> <target state="translated">Omezení pro metody přepsání a explicitní implementace rozhraní se dědí ze základní metody, nejde je tedy zadat přímo, s výjimkou omezení class nebo struct.</target> <note /> </trans-unit> <trans-unit id="ERR_AmbigOverride"> <source>The inherited members '{0}' and '{1}' have the same signature in type '{2}', so they cannot be overridden</source> <target state="translated">Zděděné členy {0} a {1} mají stejný podpis v typu {2}, takže je nejde přepsat.</target> <note /> </trans-unit> <trans-unit id="ERR_DecConstError"> <source>Evaluation of the decimal constant expression failed</source> <target state="translated">Vyhodnocování výrazu desítkové konstanty se nepovedlo.</target> <note /> </trans-unit> <trans-unit id="WRN_CmpAlwaysFalse"> <source>Comparing with null of type '{0}' always produces 'false'</source> <target state="translated">Výsledkem porovnání s hodnotou null typu {0} je vždycky false.</target> <note /> </trans-unit> <trans-unit id="WRN_CmpAlwaysFalse_Title"> <source>Comparing with null of struct type always produces 'false'</source> <target state="translated">Výsledkem porovnání s typem struct je vždycky false.</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod"> <source>Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?</source> <target state="translated">Zavedení metody Finalize může vést k potížím s voláním destruktoru. Měli jste v úmyslu deklarovat destruktor?</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod_Title"> <source>Introducing a 'Finalize' method can interfere with destructor invocation</source> <target state="translated">Zavedení metody Finalize se může rušit s vyvoláním destruktoru.</target> <note /> </trans-unit> <trans-unit id="WRN_FinalizeMethod_Description"> <source>This warning occurs when you create a class with a method whose signature is public virtual void Finalize. If such a class is used as a base class and if the deriving class defines a destructor, the destructor will override the base class Finalize method, not Finalize.</source> <target state="translated">Toto varování se objeví, pokud vytvoříte třídu s metodou, jejíž podpis je veřejný virtuální void Finalize. Pokud se taková třída používá jako základní třída a pokud odvozující třída definuje destruktor, přepíše tento destruktor metodu Finalize základní třídy, ne samotné Finalize.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplParams"> <source>'{0}' should not have a params parameter since '{1}' does not</source> <target state="translated">'Pro {0} by neměl být nastavený parametr params, protože {1} ho nemá.</target> <note /> </trans-unit> <trans-unit id="WRN_GotoCaseShouldConvert"> <source>The 'goto case' value is not implicitly convertible to type '{0}'</source> <target state="translated">Hodnotu goto case nejde implicitně převést na typ {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_GotoCaseShouldConvert_Title"> <source>The 'goto case' value is not implicitly convertible to the switch type</source> <target state="translated">Hodnotu goto case nejde implicitně převést na typ přepínače.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodImplementingAccessor"> <source>Method '{0}' cannot implement interface accessor '{1}' for type '{2}'. Use an explicit interface implementation.</source> <target state="translated">Metoda {0} nemůže implementovat přistupující objekt rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool"> <source>The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'</source> <target state="translated">Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool_Title"> <source>The result of the expression is always the same since a value of this type is never equal to 'null'</source> <target state="translated">Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool2"> <source>The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'</source> <target state="translated">Výsledek výrazu je vždycky {0}, protože hodnota typu {1} se nikdy nerovná hodnotě null typu {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_NubExprIsConstBool2_Title"> <source>The result of the expression is always the same since a value of this type is never equal to 'null'</source> <target state="translated">Výsledek výrazu je vždycky stejný, protože hodnota tohoto typu se nikdy nerovná hodnotě null.</target> <note /> </trans-unit> <trans-unit id="WRN_ExplicitImplCollision"> <source>Explicit interface implementation '{0}' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead.</source> <target state="translated">Explicitní implementace rozhraní {0} odpovídá víc než jednomu členovi rozhraní. Konkrétní výběr člena rozhraní závisí na implementaci. Zvažte možnost použití neexplicitní implementace.</target> <note /> </trans-unit> <trans-unit id="WRN_ExplicitImplCollision_Title"> <source>Explicit interface implementation matches more than one interface member</source> <target state="translated">Explicitní implementace rozhraní se shoduje s víc než jedním členem rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractHasBody"> <source>'{0}' cannot declare a body because it is marked abstract</source> <target state="translated">{0} nemůže deklarovat tělo, protože je označené jako abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_ConcreteMissingBody"> <source>'{0}' must declare a body because it is not marked abstract, extern, or partial</source> <target state="translated">{0} musí deklarovat tělo, protože je označené jako abstraktní, externí nebo částečné.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAndSealed"> <source>'{0}' cannot be both abstract and sealed</source> <target state="translated">{0} nemůže být extern i sealed.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractNotVirtual"> <source>The abstract {0} '{1}' cannot be marked virtual</source> <target state="translated">Abstraktní {0} {1} nelze označit jako virtuální.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstant"> <source>The constant '{0}' cannot be marked static</source> <target state="translated">Konstanta {0} nemůže být označená jako statická.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonFunction"> <source>'{0}': cannot override because '{1}' is not a function</source> <target state="translated">{0}: Nejde přepsat, protože {1} není funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonVirtual"> <source>'{0}': cannot override inherited member '{1}' because it is not marked virtual, abstract, or override</source> <target state="translated">{0}: Nejde přepsat zděděný člen {1}, protože není označený jako virtuální, abstraktní nebo přepis.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeAccessOnOverride"> <source>'{0}': cannot change access modifiers when overriding '{1}' inherited member '{2}'</source> <target state="translated">{0}: Při přepsání {1} zděděného členu {2} nejde měnit modifikátory přístupu.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeTupleNamesOnOverride"> <source>'{0}': cannot change tuple element names when overriding inherited member '{1}'</source> <target state="translated">{0}: při přepisu zděděného člena {1} nelze změnit prvek řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeReturnTypeOnOverride"> <source>'{0}': return type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Návratový typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantDeriveFromSealedType"> <source>'{0}': cannot derive from sealed type '{1}'</source> <target state="translated">{0}: Nejde odvozovat ze zapečetěného typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractInConcreteClass"> <source>'{0}' is abstract but it is contained in non-abstract type '{1}'</source> <target state="translated">{0} je abstraktní, ale je obsažená v neabstraktním typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstructorWithExplicitConstructorCall"> <source>'{0}': static constructor cannot have an explicit 'this' or 'base' constructor call</source> <target state="translated">{0}: Statický konstruktor nemůže používat explicitní volání konstruktoru this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticConstructorWithAccessModifiers"> <source>'{0}': access modifiers are not allowed on static constructors</source> <target state="translated">{0}: Modifikátory přístupu nejsou povolené pro statické konstruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_RecursiveConstructorCall"> <source>Constructor '{0}' cannot call itself</source> <target state="translated">Konstruktor {0} nemůže volat sám sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_IndirectRecursiveConstructorCall"> <source>Constructor '{0}' cannot call itself through another constructor</source> <target state="translated">Konstruktor {0} nemůže volat sám sebe přes jiný konstruktor.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectCallingBaseConstructor"> <source>'{0}' has no base class and cannot call a base constructor</source> <target state="translated">{0} nemá žádnou základní třídu a nemůže volat konstruktor base.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedTypeNotFound"> <source>Predefined type '{0}' is not defined or imported</source> <target state="translated">Předdefinovaný typ {0} není definovaný ani importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeNotFound"> <source>Predefined type '{0}' is not defined or imported</source> <target state="translated">Předdefinovaný typ {0} není definovaný ani importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeAmbiguous3"> <source>Predefined type '{0}' is declared in multiple referenced assemblies: '{1}' and '{2}'</source> <target state="translated">Předdefinovaný typ {0} je deklarovaný v několika odkazovaných sestaveních: {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_StructWithBaseConstructorCall"> <source>'{0}': structs cannot call base class constructors</source> <target state="translated">{0}: Struktury nemůžou volat konstruktor základní třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_StructLayoutCycle"> <source>Struct member '{0}' of type '{1}' causes a cycle in the struct layout</source> <target state="translated">Člen struktury {0} typu {1} způsobuje cyklus v rozložení struktury.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainFields"> <source>Interfaces cannot contain instance fields</source> <target state="translated">Rozhraní nemůžou obsahovat pole instance.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainConstructors"> <source>Interfaces cannot contain instance constructors</source> <target state="translated">Rozhraní nemůžou obsahovat konstruktory instance.</target> <note /> </trans-unit> <trans-unit id="ERR_NonInterfaceInInterfaceList"> <source>Type '{0}' in interface list is not an interface</source> <target state="translated">Typ {0} v seznamu rozhraní není rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceInBaseList"> <source>'{0}' is already listed in interface list</source> <target state="translated">{0} je už uvedené v seznamu rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateInterfaceWithTupleNamesInBaseList"> <source>'{0}' is already listed in the interface list on type '{2}' with different tuple element names, as '{1}'.</source> <target state="translated">{0} je již uvedeno v seznamu rozhraní u typu {2} s jinými názvy prvků řazené kolekce členů jako {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CycleInInterfaceInheritance"> <source>Inherited interface '{1}' causes a cycle in the interface hierarchy of '{0}'</source> <target state="translated">Zděděné rozhraní {1} způsobuje cyklus v hierarchii rozhraní {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_HidingAbstractMethod"> <source>'{0}' hides inherited abstract member '{1}'</source> <target state="translated">{0} skryje zděděný abstraktní člen {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedAbstractMethod"> <source>'{0}' does not implement inherited abstract member '{1}'</source> <target state="translated">{0} neimplementuje zděděný abstraktní člen {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnimplementedInterfaceMember"> <source>'{0}' does not implement interface member '{1}'</source> <target state="translated">{0} neimplementuje člen rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectCantHaveBases"> <source>The class System.Object cannot have a base class or implement an interface</source> <target state="translated">Třída System.Object nemůže mít základní třídu ani nemůže implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitInterfaceImplementationNotInterface"> <source>'{0}' in explicit interface declaration is not an interface</source> <target state="translated">{0} v explicitní deklaraci rozhraní není rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceMemberNotFound"> <source>'{0}' in explicit interface declaration is not found among members of the interface that can be implemented</source> <target state="translated">{0} v explicitní deklaraci rozhraní se nenašel mezi členy rozhraní, které se dají implementovat.</target> <note /> </trans-unit> <trans-unit id="ERR_ClassDoesntImplementInterface"> <source>'{0}': containing type does not implement interface '{1}'</source> <target state="translated">{0}: Nadřazený typ neimplementuje rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitInterfaceImplementationInNonClassOrStruct"> <source>'{0}': explicit interface declaration can only be declared in a class, record, struct or interface</source> <target state="translated">{0}: Explicitní deklaraci rozhraní se dá použít jen ve třídě, záznamu, struktuře nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberNameSameAsType"> <source>'{0}': member names cannot be the same as their enclosing type</source> <target state="translated">{0}: Názvy členů nemůžou být stejné jako názvy jejich nadřazených typů.</target> <note /> </trans-unit> <trans-unit id="ERR_EnumeratorOverflow"> <source>'{0}': the enumerator value is too large to fit in its type</source> <target state="translated">{0}: Hodnota výčtu je pro příslušný typ moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideNonProperty"> <source>'{0}': cannot override because '{1}' is not a property</source> <target state="translated">{0}: Nejde přepsat, protože {1} není vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_NoGetToOverride"> <source>'{0}': cannot override because '{1}' does not have an overridable get accessor</source> <target state="translated">{0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSetToOverride"> <source>'{0}': cannot override because '{1}' does not have an overridable set accessor</source> <target state="translated">{0}: Nejde přepsat, protože {1} neobsahuje přepsatelný přistupující objekt set.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyCantHaveVoidType"> <source>'{0}': property or indexer cannot have void type</source> <target state="translated">{0}: Vlastnost nebo indexer nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_PropertyWithNoAccessors"> <source>'{0}': property or indexer must have at least one accessor</source> <target state="translated">{0}: Vlastnost nebo indexer musí obsahovat aspoň jeden přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_NewVirtualInSealed"> <source>'{0}' is a new virtual member in sealed type '{1}'</source> <target state="translated">{0} je nový virtuální člen v zapečetěném typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyAddingAccessor"> <source>'{0}' adds an accessor not found in interface member '{1}'</source> <target state="translated">{0} přidává přistupující objekt, který se nenašel v členu rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitPropertyMissingAccessor"> <source>Explicit interface implementation '{0}' is missing accessor '{1}'</source> <target state="translated">V explicitní implementaci rozhraní {0} chybí přistupující objekt {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithInterface"> <source>'{0}': user-defined conversions to or from an interface are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na rozhraní nebo z něho nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithBase"> <source>'{0}': user-defined conversions to or from a base type are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na základní typ nebo z něj nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionWithDerived"> <source>'{0}': user-defined conversions to or from a derived type are not allowed</source> <target state="translated">{0}: Uživatelem definované převody na odvozený typ nebo z něj nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentityConversion"> <source>User-defined operator cannot convert a type to itself</source> <target state="needs-review-translation">Uživatelem definovaný operátor nemůže převzít objekt nadřazeného typu a převést jej na objekt nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionNotInvolvingContainedType"> <source>User-defined conversion must convert to or from the enclosing type</source> <target state="translated">Uživatelem definovaný převod musí převádět na nadřazený typ nebo z nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateConversionInClass"> <source>Duplicate user-defined conversion in type '{0}'</source> <target state="translated">Duplicitní uživatelem definovaný převod v typu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorsMustBeStatic"> <source>User-defined operator '{0}' must be declared static and public</source> <target state="translated">Uživatelem definovaný operátor {0} musí být deklarovaný jako static a public.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIncDecSignature"> <source>The parameter type for ++ or -- operator must be the containing type</source> <target state="translated">Typ parametru operátorů ++ a -- musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnaryOperatorSignature"> <source>The parameter of a unary operator must be the containing type</source> <target state="translated">Parametr unárního operátoru musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinaryOperatorSignature"> <source>One of the parameters of a binary operator must be the containing type</source> <target state="translated">Jeden z parametrů binárního operátoru musí být nadřazeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadShiftOperatorSignature"> <source>The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int</source> <target state="translated">První operand přetěžovaného operátoru shift musí být stejného typu jako obsahující typ a druhý operand musí být typu int.</target> <note /> </trans-unit> <trans-unit id="ERR_EnumsCantContainDefaultConstructor"> <source>Enums cannot contain explicit parameterless constructors</source> <target state="translated">Výčty nemůžou obsahovat explicitní konstruktory bez parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOverrideBogusMethod"> <source>'{0}': cannot override '{1}' because it is not supported by the language</source> <target state="translated">{0} nemůže přepsat {1}, protože ho tento jazyk nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogus"> <source>'{0}' is not supported by the language</source> <target state="translated">{0} není tímto jazykem podporovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_CantCallSpecialMethod"> <source>'{0}': cannot explicitly call operator or accessor</source> <target state="translated">{0}: Nejde explicitně volat operátor nebo přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeReference"> <source>'{0}': cannot reference a type through an expression; try '{1}' instead</source> <target state="translated">{0}: Nemůže odkazovat na typ prostřednictvím výrazu. Místo toho zkuste {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDestructorName"> <source>Name of destructor must match name of type</source> <target state="translated">Název destruktoru musí odpovídat názvu typu.</target> <note /> </trans-unit> <trans-unit id="ERR_OnlyClassesCanContainDestructors"> <source>Only class types can contain destructors</source> <target state="translated">Destruktor může být obsažený jenom v typu třída.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictAliasAndMember"> <source>Namespace '{1}' contains a definition conflicting with alias '{0}'</source> <target state="translated">Obor názvů {1} obsahuje definici, která je v konfliktu s aliasem {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingAliasAndDefinition"> <source>Alias '{0}' conflicts with {1} definition</source> <target state="translated">Alias {0} je v konfliktu s definicí {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnSpecialMethod"> <source>The Conditional attribute is not valid on '{0}' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation</source> <target state="needs-review-translation">Atribut Conditional není pro {0} platný, protože je to konstruktor, destruktor, operátor nebo explicitní implementace rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalMustReturnVoid"> <source>The Conditional attribute is not valid on '{0}' because its return type is not void</source> <target state="translated">Atribut Conditional není pro {0} platný, protože jeho návratový kód není void.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAttribute"> <source>Duplicate '{0}' attribute</source> <target state="translated">Duplicitní atribut {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAttributeInNetModule"> <source>Duplicate '{0}' attribute in '{1}'</source> <target state="translated">Duplicitní atribut {0} v {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnInterfaceMethod"> <source>The Conditional attribute is not valid on interface members</source> <target state="translated">Pro členy rozhraní je atribut Conditional neplatný.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorCantReturnVoid"> <source>User-defined operators cannot return void</source> <target state="translated">Operátory definované uživatelem nemůžou vracet typ void.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicConversion"> <source>'{0}': user-defined conversions to or from the dynamic type are not allowed</source> <target state="translated">{0}: Uživatelsky definované převody na dynamický typ nebo z dynamického typu nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAttributeArgument"> <source>Invalid value for argument to '{0}' attribute</source> <target state="translated">Neplatná hodnota pro argument u atributu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterNotValidForType"> <source>Parameter not valid for the specified unmanaged type.</source> <target state="translated">Parametr není platný pro zadaný nespravovaný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired1"> <source>Attribute parameter '{0}' must be specified.</source> <target state="translated">Parametr atributu {0} musí být zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeParameterRequired2"> <source>Attribute parameter '{0}' or '{1}' must be specified.</source> <target state="translated">Parametr atributu {0} nebo {1} musí být zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeNotValidForFields"> <source>Unmanaged type '{0}' not valid for fields.</source> <target state="translated">Nespravovaný typ {0} není platný pro pole.</target> <note /> </trans-unit> <trans-unit id="ERR_MarshalUnmanagedTypeOnlyValidForFields"> <source>Unmanaged type '{0}' is only valid for fields.</source> <target state="translated">Nespravovaný typ {0} je platný jenom pro pole.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeOnBadSymbolType"> <source>Attribute '{0}' is not valid on this declaration type. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro deklaraci tohoto typu. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FloatOverflow"> <source>Floating-point constant is outside the range of type '{0}'</source> <target state="translated">Konstanta s pohyblivou řádovou čárkou je mimo rozsah typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithoutUuidAttribute"> <source>The Guid attribute must be specified with the ComImport attribute</source> <target state="translated">Atribut Guid musí být zadaný současně s atributem ComImport.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNamedArgument"> <source>Invalid value for named attribute argument '{0}'</source> <target state="translated">Neplatná hodnota argumentu {0} pojmenovaného atributu</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnInvalidMethod"> <source>The DllImport attribute must be specified on a method marked 'static' and 'extern'</source> <target state="translated">Pro metodu s deklarací static a extern musí být zadaný atribut DllImport.</target> <note /> </trans-unit> <trans-unit id="ERR_EncUpdateFailedMissingAttribute"> <source>Cannot update '{0}'; attribute '{1}' is missing.</source> <target state="translated">Nelze aktualizovat {0}; chybí atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DllImportOnGenericMethod"> <source>The DllImport attribute cannot be applied to a method that is generic or contained in a generic method or type.</source> <target state="translated">Atribut DllImport se nedá použít u metody, která je obecná nebo obsažená v obecné metodě nebo typu.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldCantBeRefAny"> <source>Field or property cannot be of type '{0}'</source> <target state="translated">Pole nebo vlastnost nemůže být typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldAutoPropCantBeByRefLike"> <source>Field or auto-implemented property cannot be of type '{0}' unless it is an instance member of a ref struct.</source> <target state="translated">Vlastnost pole nebo automaticky implementovaná vlastnost nemůže být typu {0}, pokud není členem instance struktury REF.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayElementCantBeRefAny"> <source>Array elements cannot be of type '{0}'</source> <target state="translated">Prvky pole nemůžou být typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbol"> <source>'{0}' is obsolete</source> <target state="translated">'Prvek {0} je zastaralý.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbol_Title"> <source>Type or member is obsolete</source> <target state="translated">Typ nebo člen je zastaralý.</target> <note /> </trans-unit> <trans-unit id="ERR_NotAnAttributeClass"> <source>'{0}' is not an attribute class</source> <target state="translated">{0} není třída atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedAttributeArgument"> <source>'{0}' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static.</source> <target state="translated">{0} není platný argument pojmenovaného atributu. Argumenty pojmenovaného atributu musí být pole, pro která nebyla použitá deklarace readonly, static ani const, nebo vlastnosti pro čtení i zápis, které jsou veřejné a nejsou statické.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbolStr"> <source>'{0}' is obsolete: '{1}'</source> <target state="translated">{0} je zastaralá: {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedSymbolStr_Title"> <source>Type or member is obsolete</source> <target state="translated">Typ nebo člen je zastaralý.</target> <note /> </trans-unit> <trans-unit id="ERR_DeprecatedSymbolStr"> <source>'{0}' is obsolete: '{1}'</source> <target state="translated">{0} je zastaralá: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerCantHaveVoidType"> <source>Indexers cannot have void type</source> <target state="translated">Indexer nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_VirtualPrivate"> <source>'{0}': virtual or abstract members cannot be private</source> <target state="translated">{0}: Virtuální nebo abstraktní členy nemůžou být privátní.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitToNonArrayType"> <source>Can only use array initializer expressions to assign to array types. Try using a new expression instead.</source> <target state="translated">Výrazy inicializátoru pole jde používat jenom pro přiřazení k typům pole. Zkuste použít výraz new.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitInBadPlace"> <source>Array initializers can only be used in a variable or field initializer. Try using a new expression instead.</source> <target state="translated">Inicializátory pole jde používat jenom v inicializátoru pole nebo proměnné. Zkuste použít výraz new.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingStructOffset"> <source>'{0}': instance field in types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute</source> <target state="translated">{0}: Typy polí instance označené deklarací StructLayout(LayoutKind.Explicit) musí mít atribut FieldOffset.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternMethodNoImplementation"> <source>Method, operator, or accessor '{0}' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation.</source> <target state="translated">Metoda, operátor nebo přistupující objekt {0} je označený jako externí a nemá žádné atributy. Zvažte možnost přidání atributu DllImport k určení externí implementace.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternMethodNoImplementation_Title"> <source>Method, operator, or accessor is marked external and has no attributes on it</source> <target state="translated">Metoda, operátor nebo přistupující objekt používá deklaraci external a nemá žádné atributy.</target> <note /> </trans-unit> <trans-unit id="WRN_ProtectedInSealed"> <source>'{0}': new protected member declared in sealed type</source> <target state="translated">{0}: V zapečetěném typu je deklarovaný nový chráněný člen.</target> <note /> </trans-unit> <trans-unit id="WRN_ProtectedInSealed_Title"> <source>New protected member declared in sealed type</source> <target state="translated">V zapečetěném typu je deklarovaný nový chráněný člen</target> <note /> </trans-unit> <trans-unit id="ERR_InterfaceImplementedByConditional"> <source>Conditional member '{0}' cannot implement interface member '{1}' in type '{2}'</source> <target state="translated">Podmíněný člen {0} nemůže implementovat člen rozhraní {1} v typu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalRefParam"> <source>ref and out are not valid in this context</source> <target state="translated">Atributy ref a out nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgumentToAttribute"> <source>The argument to the '{0}' attribute must be a valid identifier</source> <target state="translated">Argument atributu {0} musí být platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_StructOffsetOnBadStruct"> <source>The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)</source> <target state="translated">Atribut FieldOffset jde použít jenom pro členy typů s deklarací StructLayout(LayoutKind.Explicit).</target> <note /> </trans-unit> <trans-unit id="ERR_StructOffsetOnBadField"> <source>The FieldOffset attribute is not allowed on static or const fields</source> <target state="translated">Atribut FieldOffset není povolený pro pole typu static nebo const.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeUsageOnNonAttributeClass"> <source>Attribute '{0}' is only valid on classes derived from System.Attribute</source> <target state="translated">Atribut {0} je platný jenom pro třídy odvozené od třídy System.Attribute.</target> <note /> </trans-unit> <trans-unit id="WRN_PossibleMistakenNullStatement"> <source>Possible mistaken empty statement</source> <target state="translated">Možná chybný prázdný příkaz</target> <note /> </trans-unit> <trans-unit id="WRN_PossibleMistakenNullStatement_Title"> <source>Possible mistaken empty statement</source> <target state="translated">Možná chybný prázdný příkaz</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedAttributeArgument"> <source>'{0}' duplicate named attribute argument</source> <target state="translated">'Duplicitní argument pojmenovaného atributu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromEnumOrValueType"> <source>'{0}' cannot derive from special class '{1}'</source> <target state="translated">{0} se nemůže odvozovat ze speciální třídy {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultMemberOnIndexedType"> <source>Cannot specify the DefaultMember attribute on a type containing an indexer</source> <target state="translated">Atribut DefaultMember nejde zadat pro typ obsahující indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_BogusType"> <source>'{0}' is a type not supported by the language</source> <target state="translated">'Typ {0} není tímto jazykem podporovaný.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedInternalField"> <source>Field '{0}' is never assigned to, and will always have its default value {1}</source> <target state="translated">Do pole {0} se nikdy nic nepřiřadí. Bude mít vždy výchozí hodnotu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnassignedInternalField_Title"> <source>Field is never assigned to, and will always have its default value</source> <target state="translated">Do pole se nikdy nic nepřiřadí. Bude mít vždycky výchozí hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_CStyleArray"> <source>Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.</source> <target state="translated">Chybný deklarátor pole. Při deklaraci spravovaného pole musí být specifikátor rozměru uvedený před identifikátorem proměnné. Při deklaraci pole vyrovnávací paměti pevné velikosti uveďte před typem pole klíčové slovo fixed.</target> <note /> </trans-unit> <trans-unit id="WRN_VacuousIntegralComp"> <source>Comparison to integral constant is useless; the constant is outside the range of type '{0}'</source> <target state="translated">Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_VacuousIntegralComp_Title"> <source>Comparison to integral constant is useless; the constant is outside the range of the type</source> <target state="translated">Porovnání s integrální konstantou je zbytečné; hodnota konstanty je mimo rozsah typu.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractAttributeClass"> <source>Cannot apply attribute class '{0}' because it is abstract</source> <target state="translated">Nejde použít třídu atributů {0}, protože je abstraktní.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedAttributeArgumentType"> <source>'{0}' is not a valid named attribute argument because it is not a valid attribute parameter type</source> <target state="translated">{0} není platný argument pojmenovaného atributu, protože se nejedná o platný typ parametru atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPredefinedMember"> <source>Missing compiler required member '{0}.{1}'</source> <target state="translated">Požadovaný člen {0}.{1} kompilátoru se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeLocationOnBadDeclaration"> <source>'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored.</source> <target state="translated">{0} není platné umístění atributu pro tuto deklaraci. Platnými umístěními atributů pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeLocationOnBadDeclaration_Title"> <source>Not a valid attribute location for this declaration</source> <target state="translated">Není platné umístění atributu pro tuto deklaraci.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAttributeLocation"> <source>'{0}' is not a recognized attribute location. Valid attribute locations for this declaration are '{1}'. All attributes in this block will be ignored.</source> <target state="translated">{0} není známé umístění atributu. Platná umístění atributu pro tuto deklaraci jsou {1}. Všechny atributy v tomto bloku se budou ignorovat.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAttributeLocation_Title"> <source>Not a recognized attribute location</source> <target state="translated">Není rozpoznané umístění atributu.</target> <note /> </trans-unit> <trans-unit id="WRN_EqualsWithoutGetHashCode"> <source>'{0}' overrides Object.Equals(object o) but does not override Object.GetHashCode()</source> <target state="translated">{0} přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualsWithoutGetHashCode_Title"> <source>Type overrides Object.Equals(object o) but does not override Object.GetHashCode()</source> <target state="translated">Typ přepisuje Object.Equals(object o), ale nepřepisuje Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutEquals"> <source>'{0}' defines operator == or operator != but does not override Object.Equals(object o)</source> <target state="translated">{0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o).</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutEquals_Title"> <source>Type defines operator == or operator != but does not override Object.Equals(object o)</source> <target state="translated">Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.Equals(object o).</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutGetHashCode"> <source>'{0}' defines operator == or operator != but does not override Object.GetHashCode()</source> <target state="translated">{0} definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="WRN_EqualityOpWithoutGetHashCode_Title"> <source>Type defines operator == or operator != but does not override Object.GetHashCode()</source> <target state="translated">Typ definuje operátor == nebo !=, ale nepřepisuje funkci Object.GetHashCode().</target> <note /> </trans-unit> <trans-unit id="ERR_OutAttrOnRefParam"> <source>Cannot specify the Out attribute on a ref parameter without also specifying the In attribute.</source> <target state="translated">Nejde specifikovat atribut Out pro referenční parametr, když není současně specifikovaný atribut In.</target> <note /> </trans-unit> <trans-unit id="ERR_OverloadRefKind"> <source>'{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}'</source> <target state="translated">{0} nemůže definovat přetíženou {1}, která se liší jenom v modifikátorech parametrů {2} a {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_LiteralDoubleCast"> <source>Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type</source> <target state="translated">Literály typu double nejde implicitně převést na typ {1}. Chcete-li vytvořit literál tohoto typu, použijte předponu {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_IncorrectBooleanAssg"> <source>Assignment in conditional expression is always constant; did you mean to use == instead of = ?</source> <target state="translated">Přiřazení je v podmíněných výrazech vždy konstantní. Nechtěli jste spíše použít operátor == místo operátoru = ?</target> <note /> </trans-unit> <trans-unit id="WRN_IncorrectBooleanAssg_Title"> <source>Assignment in conditional expression is always constant</source> <target state="translated">Přiřazení je v podmíněných výrazech vždycky konstantní.</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedInStruct"> <source>'{0}': new protected member declared in struct</source> <target state="translated">{0}: Ve struktuře je deklarovaný nový chráněný člen.</target> <note /> </trans-unit> <trans-unit id="ERR_InconsistentIndexerNames"> <source>Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type</source> <target state="translated">Dva indexery mají stejný název. Atribut IndexerName musí být v rámci jednoho typu použitý se stejným názvem pro každý indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithUserCtor"> <source>A class with the ComImport attribute cannot have a user-defined constructor</source> <target state="translated">Třída s atributem ComImport nemůže mít konstruktor definovaný uživatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldCantHaveVoidType"> <source>Field cannot have void type</source> <target state="translated">Pole nemůže být typu void.</target> <note /> </trans-unit> <trans-unit id="WRN_NonObsoleteOverridingObsolete"> <source>Member '{0}' overrides obsolete member '{1}'. Add the Obsolete attribute to '{0}'.</source> <target state="translated">Člen {0} přepisuje zastaralý člen {1}. Přidejte ke členu {0} atribut Obsolete.</target> <note /> </trans-unit> <trans-unit id="WRN_NonObsoleteOverridingObsolete_Title"> <source>Member overrides obsolete member</source> <target state="translated">Člen přepisuje nezastaralý člen.</target> <note /> </trans-unit> <trans-unit id="ERR_SystemVoid"> <source>System.Void cannot be used from C# -- use typeof(void) to get the void type object</source> <target state="translated">Nejde použít konstrukci System.Void jazyka C#. Objekt typu void získáte pomocí syntaxe typeof(void).</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitParamArray"> <source>Do not use 'System.ParamArrayAttribute'. Use the 'params' keyword instead.</source> <target state="translated">Nepoužívejte atribut System.ParamArrayAttribute. Použijte místo něj klíčové slovo params.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend"> <source>Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first</source> <target state="translated">Logický bitový operátor or se použil pro operand s rozšířeným podpisem. Zvažte nejprve možnost přetypování na menší nepodepsaný typ.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend_Title"> <source>Bitwise-or operator used on a sign-extended operand</source> <target state="translated">Bitový operátor or byl použitý pro operand s rozšířeným podpisem.</target> <note /> </trans-unit> <trans-unit id="WRN_BitwiseOrSignExtend_Description"> <source>The compiler implicitly widened and sign-extended a variable, and then used the resulting value in a bitwise OR operation. This can result in unexpected behavior.</source> <target state="translated">Kompilátor implicitně rozšířil proměnnou a doplnil k ní podpis. Výslednou hodnotu pak použil v bitovém porovnání NEBO operaci. Výsledkem může být neočekávané chování.</target> <note /> </trans-unit> <trans-unit id="ERR_VolatileStruct"> <source>'{0}': a volatile field cannot be of the type '{1}'</source> <target state="translated">{0}: Pole s modifikátorem volatile nemůže být {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_VolatileAndReadonly"> <source>'{0}': a field cannot be both volatile and readonly</source> <target state="translated">{0}: U pole nejde použít současně volatile i readonly.</target> <note /> </trans-unit> <trans-unit id="ERR_AbstractField"> <source>The modifier 'abstract' is not valid on fields. Try using a property instead.</source> <target state="translated">Modifikátor abstract není pro pole platný. Místo něho zkuste použít vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_BogusExplicitImpl"> <source>'{0}' cannot implement '{1}' because it is not supported by the language</source> <target state="translated">{0} nemůže implementovat {1}, protože ho tento jazyk nepodporuje.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitMethodImplAccessor"> <source>'{0}' explicit method implementation cannot implement '{1}' because it is an accessor</source> <target state="translated">'Explicitní implementace metody {0} nemůže implementovat {1}, protože se jedná o přistupující objekt.</target> <note /> </trans-unit> <trans-unit id="WRN_CoClassWithoutComImport"> <source>'{0}' interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute'</source> <target state="translated">'Rozhraní {0} s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CoClassWithoutComImport_Title"> <source>Interface marked with 'CoClassAttribute' not marked with 'ComImportAttribute'</source> <target state="translated">Rozhraní s deklarací CoClassAttribute neobsahuje deklaraci ComImportAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalWithOutParam"> <source>Conditional member '{0}' cannot have an out parameter</source> <target state="translated">Podmíněný člen {0} nemůže mít parametr out.</target> <note /> </trans-unit> <trans-unit id="ERR_AccessorImplementingMethod"> <source>Accessor '{0}' cannot implement interface member '{1}' for type '{2}'. Use an explicit interface implementation.</source> <target state="translated">Přistupující objekt {0} nemůže implementovat člen rozhraní {1} pro typ {2}. Použijte explicitní implementaci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasQualAsExpression"> <source>The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead.</source> <target state="translated">Kvalifikátor aliasu oboru názvů (::) se vždycky vyhodnotí jako typ nebo obor názvů, takže je tady neplatný. Místo něho zvažte použití kvalifikátoru . (tečka).</target> <note /> </trans-unit> <trans-unit id="ERR_DerivingFromATyVar"> <source>Cannot derive from '{0}' because it is a type parameter</source> <target state="translated">Nejde odvozovat z parametru {0}, protože je to parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeParameter"> <source>Duplicate type parameter '{0}'</source> <target state="translated">Duplicitní parametr typu {0}</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterTypeParameter"> <source>Type parameter '{0}' has the same name as the type parameter from outer type '{1}'</source> <target state="translated">Parametr typu {0} má stejný název jako parametr typu z vnějšího typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_TypeParameterSameAsOuterTypeParameter_Title"> <source>Type parameter has the same name as the type parameter from outer type</source> <target state="translated">Parametr typu má stejný název jako parametr typu z vnějšího typu.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVariableSameAsParent"> <source>Type parameter '{0}' has the same name as the containing type, or method</source> <target state="translated">Parametr typu {0} má stejný název jako nadřazený typ nebo metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_UnifyingInterfaceInstantiations"> <source>'{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions</source> <target state="translated">{0} nemůže implementovat {1} a zároveň {2}, protože u některých náhrad parametrů typu může dojít k jejich sjednocení.</target> <note /> </trans-unit> <trans-unit id="ERR_TyVarNotFoundInConstraint"> <source>'{1}' does not define type parameter '{0}'</source> <target state="translated">{1} nedefinuje parametr typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBoundType"> <source>'{0}' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</source> <target state="translated">{0} není platné omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_SpecialTypeAsBound"> <source>Constraint cannot be special class '{0}'</source> <target state="translated">Omezení nemůže být speciální třída {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisBound"> <source>Inconsistent accessibility: constraint type '{1}' is less accessible than '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ omezení {1} je míň dostupný než {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_LookupInTypeVariable"> <source>Cannot do member lookup in '{0}' because it is a type parameter</source> <target state="translated">Nejde vyhledávat člena v {0}, protože se jedná o parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadConstraintType"> <source>Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter.</source> <target state="translated">Neplatný typ omezení. Typ použitý jako omezení musí být rozhraní, nezapečetěná třída nebo parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_InstanceMemberInStaticClass"> <source>'{0}': cannot declare instance members in a static class</source> <target state="translated">{0}: Nejde deklarovat členy instance ve statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticBaseClass"> <source>'{1}': cannot derive from static class '{0}'</source> <target state="translated">{1}: Nejde odvodit ze statické třídy {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructorInStaticClass"> <source>Static classes cannot have instance constructors</source> <target state="translated">Statické třídy nemůžou mít konstruktory instancí.</target> <note /> </trans-unit> <trans-unit id="ERR_DestructorInStaticClass"> <source>Static classes cannot contain destructors</source> <target state="translated">Statické třídy nemůžou obsahovat destruktory.</target> <note /> </trans-unit> <trans-unit id="ERR_InstantiatingStaticClass"> <source>Cannot create an instance of the static class '{0}'</source> <target state="translated">Nejde vytvořit instanci statické třídy {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticDerivedFromNonObject"> <source>Static class '{0}' cannot derive from type '{1}'. Static classes must derive from object.</source> <target state="translated">Statická třída {0} se nemůže odvozovat z typu {1}. Tyto třídy se musí odvozovat z objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticClassInterfaceImpl"> <source>'{0}': static classes cannot implement interfaces</source> <target state="translated">{0}: Statické třídy nemůžou implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_RefStructInterfaceImpl"> <source>'{0}': ref structs cannot implement interfaces</source> <target state="translated">{0}: Struktury REF nemůžou implementovat rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_OperatorInStaticClass"> <source>'{0}': static classes cannot contain user-defined operators</source> <target state="translated">{0}: Statické třídy nemůžou obsahovat operátory definované uživatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_ConvertToStaticClass"> <source>Cannot convert to static type '{0}'</source> <target state="translated">Nejde převést na statický typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstraintIsStaticClass"> <source>'{0}': static classes cannot be used as constraints</source> <target state="translated">{0}: Statické třídy nejde používat jako omezení.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericArgIsStaticClass"> <source>'{0}': static types cannot be used as type arguments</source> <target state="translated">{0}: Statické typy nejde používat jako argumenty typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayOfStaticClass"> <source>'{0}': array elements cannot be of static type</source> <target state="translated">{0}: Prvky pole nemůžou být statického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerInStaticClass"> <source>'{0}': cannot declare indexers in a static class</source> <target state="translated">{0}: Nejde deklarovat indexery ve statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_ParameterIsStaticClass"> <source>'{0}': static types cannot be used as parameters</source> <target state="translated">{0}: Statické typy nejde používat jako parametry.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnTypeIsStaticClass"> <source>'{0}': static types cannot be used as return types</source> <target state="translated">{0}: Statické typy nejde používat jako typy vracených hodnot.</target> <note /> </trans-unit> <trans-unit id="ERR_VarDeclIsStaticClass"> <source>Cannot declare a variable of static type '{0}'</source> <target state="translated">Nejde deklarovat proměnnou statického typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmptyThrowInFinally"> <source>A throw statement with no arguments is not allowed in a finally clause that is nested inside the nearest enclosing catch clause</source> <target state="translated">Příkaz throw bez argumentů není povolený v klauzuli finally, která je vnořená do nejbližší uzavírající klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSpecifier"> <source>'{0}' is not a valid format specifier</source> <target state="translated">{0} není platným specifikátorem formátu.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToLockOrDispose"> <source>Possibly incorrect assignment to local '{0}' which is the argument to a using or lock statement. The Dispose call or unlocking will happen on the original value of the local.</source> <target state="translated">Možná existuje nesprávné přiřazení místní proměnné {0}, která je argumentem příkazu using nebo lock. Volání Dispose nebo odemknutí se provede u původní hodnoty místní proměnné.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToLockOrDispose_Title"> <source>Possibly incorrect assignment to local which is the argument to a using or lock statement</source> <target state="translated">Pravděpodobně nesprávné přiřazení místní hodnotě, která je argumentem příkazu using nebo lock</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeInThisAssembly"> <source>Type '{0}' is defined in this assembly, but a type forwarder is specified for it</source> <target state="translated">V tomto sestavení je definovaný typ {0}, je ale pro něj zadané předávání typů.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeIsNested"> <source>Cannot forward type '{0}' because it is a nested type of '{1}'</source> <target state="translated">Nejde předat typ {0}, protože se jedná o vnořený typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CycleInTypeForwarder"> <source>The type forwarder for type '{0}' in assembly '{1}' causes a cycle</source> <target state="translated">Předávání typů pro typ {0} v sestavení {1} způsobuje zacyklení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblyNameOnNonModule"> <source>The /moduleassemblyname option may only be specified when building a target type of 'module'</source> <target state="translated">Parametr /moduleassemblyname jde zadat jenom při vytváření typu cíle module.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFwdType"> <source>Invalid type specified as an argument for TypeForwardedTo attribute</source> <target state="translated">Neplatný typ zadaný jako argument atributu TypeForwardedTo</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberStatic"> <source>'{0}' does not implement instance interface member '{1}'. '{2}' cannot implement the interface member because it is static.</source> <target state="needs-review-translation">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože je statické.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberNotPublic"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement an interface member because it is not public.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen rozhraní, protože není veřejné.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongReturnType"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have the matching return type of '{3}'.</source> <target state="translated">{0} neimplementuje člen rozhraní {1}. {2} nemůže implementovat člen {1}, protože nemá odpovídající návratový typ {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateTypeForwarder"> <source>'{0}' duplicate TypeForwardedToAttribute</source> <target state="translated">'Duplicitní TypeForwardedToAttribute {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSelectOrGroup"> <source>A query body must end with a select clause or a group clause</source> <target state="translated">Za tělem dotazu musí následovat klauzule select nebo group.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordOn"> <source>Expected contextual keyword 'on'</source> <target state="translated">Očekávalo se kontextové klíčové slovo on.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordEquals"> <source>Expected contextual keyword 'equals'</source> <target state="translated">Očekávalo se kontextové klíčové slovo equals.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedContextualKeywordBy"> <source>Expected contextual keyword 'by'</source> <target state="translated">Očekávalo se kontextové klíčové slovo by.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAnonymousTypeMemberDeclarator"> <source>Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.</source> <target state="translated">Neplatný deklarátor členu anonymního typu. Členy anonymního typu musí být deklarované přiřazením členu, prostým názvem nebo přístupem k členu.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInitializerElementInitializer"> <source>Invalid initializer member declarator</source> <target state="translated">Neplatný deklarátor členu inicializátoru</target> <note /> </trans-unit> <trans-unit id="ERR_InconsistentLambdaParameterUsage"> <source>Inconsistent lambda parameter usage; parameter types must be all explicit or all implicit</source> <target state="translated">Nekonzistentní použití parametru lambda. Typy parametrů musí být buď všechny explicitní, nebo všechny implicitní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInvalidModifier"> <source>A partial method cannot have the 'abstract' modifier</source> <target state="translated">Částečná metoda nemůže mít modifikátor abstract.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyInPartialClass"> <source>A partial method must be declared within a partial type</source> <target state="translated">Částečná metoda musí být deklarovaná uvnitř částečného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodNotExplicit"> <source>A partial method may not explicitly implement an interface method</source> <target state="translated">Částečná metoda nesmí explicitně implementovat metodu rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodExtensionDifference"> <source>Both partial method declarations must be extension methods or neither may be an extension method</source> <target state="translated">Obě deklarace částečné metody musí deklarovat metody rozšíření, nebo nesmí metodu rozšíření deklarovat žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyOneLatent"> <source>A partial method may not have multiple defining declarations</source> <target state="translated">Částečná metoda nesmí mít víc definujících deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodOnlyOneActual"> <source>A partial method may not have multiple implementing declarations</source> <target state="translated">Částečná metoda nesmí mít víc implementujících deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodParamsDifference"> <source>Both partial method declarations must use a params parameter or neither may use a params parameter</source> <target state="translated">Obě deklarace částečné metody musí používat parametr params nebo ho nepoužívat.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodMustHaveLatent"> <source>No defining declaration found for implementing declaration of partial method '{0}'</source> <target state="translated">Nenašla se žádná definující deklarace pro implementující deklaraci částečné metody {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInconsistentTupleNames"> <source>Both partial method declarations, '{0}' and '{1}', must use the same tuple element names.</source> <target state="translated">V deklaracích metod, {0} a {1} se musí používat stejné názvy prvků řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInconsistentConstraints"> <source>Partial method declarations of '{0}' have inconsistent constraints for type parameter '{1}'</source> <target state="translated">Částečné deklarace metod {0} mají nekonzistentní omezení parametru typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodToDelegate"> <source>Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration</source> <target state="translated">Nejde vytvořit delegáta z metody {0}, protože se jedná o částečnou metodu bez implementující deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodStaticDifference"> <source>Both partial method declarations must be static or neither may be static</source> <target state="translated">Obě deklarace částečné metody musí být statické, nebo nesmí být statická žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodUnsafeDifference"> <source>Both partial method declarations must be unsafe or neither may be unsafe</source> <target state="translated">Obě deklarace částečné metody musí být nezabezpečené, nebo nesmí být nezabezpečená žádná z nich.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialMethodInExpressionTree"> <source>Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees</source> <target state="translated">Ve stromech výrazů nejde používat částečné metody, pro které existuje jenom definující deklarace, nebo odebrané podmíněné metody.</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteOverridingNonObsolete"> <source>Obsolete member '{0}' overrides non-obsolete member '{1}'</source> <target state="translated">Zastaralý člen {0} potlačuje nezastaralý člen {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ObsoleteOverridingNonObsolete_Title"> <source>Obsolete member overrides non-obsolete member</source> <target state="translated">Zastaralý člen přepisuje nezastaralý člen.</target> <note /> </trans-unit> <trans-unit id="WRN_DebugFullNameTooLong"> <source>The fully qualified name for '{0}' is too long for debug information. Compile without '/debug' option.</source> <target state="translated">Plně kvalifikovaný název {0} je moc dlouhý pro vygenerování ladicích informací. Z kompilace vyřaďte možnost /debug.</target> <note /> </trans-unit> <trans-unit id="WRN_DebugFullNameTooLong_Title"> <source>Fully qualified name is too long for debug information</source> <target state="translated">Plně kvalifikovaný název je pro ladicí informace moc dlouhý.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableAssignedBadValue"> <source>Cannot assign {0} to an implicitly-typed variable</source> <target state="translated">{0} nejde přiřadit k proměnné s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableWithNoInitializer"> <source>Implicitly-typed variables must be initialized</source> <target state="translated">Proměnné s implicitním typem musí být inicializované.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableMultipleDeclarator"> <source>Implicitly-typed variables cannot have multiple declarators</source> <target state="translated">Proměnné s implicitním typem nemůžou mít víc deklarátorů.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableAssignedArrayInitializer"> <source>Cannot initialize an implicitly-typed variable with an array initializer</source> <target state="translated">Proměnnou s implicitním typem nejde inicializovat inicializátorem pole.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedLocalCannotBeFixed"> <source>Implicitly-typed local variables cannot be fixed</source> <target state="translated">Lokální proměnné s implicitním typem nemůžou být pevné.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedVariableCannotBeConst"> <source>Implicitly-typed variables cannot be constant</source> <target state="translated">Proměnné s implicitním typem nemůžou být konstanty.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternCtorNoImplementation"> <source>Constructor '{0}' is marked external</source> <target state="translated">Konstruktor {0} je označený jako externí.</target> <note /> </trans-unit> <trans-unit id="WRN_ExternCtorNoImplementation_Title"> <source>Constructor is marked external</source> <target state="translated">Konstruktor je označený jako externí.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarNotFound"> <source>The contextual keyword 'var' may only appear within a local variable declaration or in script code</source> <target state="translated">Kontextové klíčové slovo var se může objevit pouze v rámci deklarace lokální proměnné nebo v kódu skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedArrayNoBestType"> <source>No best type found for implicitly-typed array</source> <target state="translated">Nebyl nalezen optimální typ pro implicitně typované pole.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypePropertyAssignedBadValue"> <source>Cannot assign '{0}' to anonymous type property</source> <target state="translated">{0} nejde přiřadit k anonymní vlastnosti typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsBaseAccess"> <source>An expression tree may not contain a base access</source> <target state="translated">Strom výrazu nesmí obsahovat základní přístup.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAssignment"> <source>An expression tree may not contain an assignment operator</source> <target state="translated">Strom výrazu nesmí obsahovat operátor přiřazení.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeDuplicatePropertyName"> <source>An anonymous type cannot have multiple properties with the same name</source> <target state="translated">Anonymní typ nemůže mít více vlastností se stejným názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_StatementLambdaToExpressionTree"> <source>A lambda expression with a statement body cannot be converted to an expression tree</source> <target state="translated">Výraz lambda s tělem příkazu nejde převést na strom výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeMustHaveDelegate"> <source>Cannot convert lambda to an expression tree whose type argument '{0}' is not a delegate type</source> <target state="translated">Výraz lambda nejde převést na strom výrazu, jehož argument typu {0} neurčuje delegovaný typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousTypeNotAvailable"> <source>Cannot use anonymous type in a constant expression</source> <target state="translated">V konstantním výrazu nejde použít anonymní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_LambdaInIsAs"> <source>The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group.</source> <target state="translated">Prvním operandem operátoru is nebo as nesmí být výraz lambda, anonymní metoda ani skupina metod.</target> <note /> </trans-unit> <trans-unit id="ERR_TypelessTupleInAs"> <source>The first operand of an 'as' operator may not be a tuple literal without a natural type.</source> <target state="translated">První operand operátoru as nesmí být literál řazené kolekce členů bez přirozeného typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer"> <source>An expression tree may not contain a multidimensional array initializer</source> <target state="translated">Strom výrazu nesmí obsahovat inicializátor vícedimenzionálního pole.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingArgument"> <source>Argument missing</source> <target state="translated">Chybí argument.</target> <note /> </trans-unit> <trans-unit id="ERR_VariableUsedBeforeDeclaration"> <source>Cannot use local variable '{0}' before it is declared</source> <target state="translated">Lokální proměnnou {0} nejde použít dřív, než je deklarovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_RecursivelyTypedVariable"> <source>Type of '{0}' cannot be inferred since its initializer directly or indirectly refers to the definition.</source> <target state="translated">Typ pro {0} nejde odvodit, protože jeho inicializátor přímo nebo nepřímo odkazuje na definici.</target> <note /> </trans-unit> <trans-unit id="ERR_UnassignedThisAutoProperty"> <source>Auto-implemented property '{0}' must be fully assigned before control is returned to the caller.</source> <target state="translated">Před vrácením řízení volajícímu modulu musí být plně přiřazená automaticky implementovaná vlastnost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_VariableUsedBeforeDeclarationAndHidesField"> <source>Cannot use local variable '{0}' before it is declared. The declaration of the local variable hides the field '{1}'.</source> <target state="translated">Lokální proměnnou {0} nejde použít dřív, než je deklarovaná. Deklarace lokální proměnné skryje pole {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsBadCoalesce"> <source>An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side</source> <target state="translated">Strom výrazu lambda nesmí obsahovat operátor sloučení, na jehož levé straně stojí literál s hodnotou Null nebo výchozí literál.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentifierExpected"> <source>Identifier expected</source> <target state="translated">Očekával se identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_SemicolonExpected"> <source>; expected</source> <target state="translated">Očekával se středník (;).</target> <note /> </trans-unit> <trans-unit id="ERR_SyntaxError"> <source>Syntax error, '{0}' expected</source> <target state="translated">Chyba syntaxe; očekávána hodnota: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateModifier"> <source>Duplicate '{0}' modifier</source> <target state="translated">Duplicitní modifikátor {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAccessor"> <source>Property accessor already defined</source> <target state="translated">Přistupující objekt vlastnosti je už definovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_IntegralTypeExpected"> <source>Type byte, sbyte, short, ushort, int, uint, long, or ulong expected</source> <target state="translated">Očekával se typ byte, sbyte, short, ushort, int, uint, long nebo ulong.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalEscape"> <source>Unrecognized escape sequence</source> <target state="translated">Nerozpoznaná řídicí sekvence</target> <note /> </trans-unit> <trans-unit id="ERR_NewlineInConst"> <source>Newline in constant</source> <target state="translated">Konstanta obsahuje znak nového řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyCharConst"> <source>Empty character literal</source> <target state="translated">Prázdný znakový literál</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyCharsInConst"> <source>Too many characters in character literal</source> <target state="translated">Příliš moc znaků ve znakovém literálu</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidNumber"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="ERR_GetOrSetExpected"> <source>A get or set accessor expected</source> <target state="translated">Očekával se přistupující objekt get nebo set.</target> <note /> </trans-unit> <trans-unit id="ERR_ClassTypeExpected"> <source>An object, string, or class type expected</source> <target state="translated">Očekával se typ object, string nebo class.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentExpected"> <source>Named attribute argument expected</source> <target state="translated">Očekával se argument pojmenovaného atributu.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyCatches"> <source>Catch clauses cannot follow the general catch clause of a try statement</source> <target state="translated">Klauzule catch nemůžou následovat za obecnou klauzulí catch příkazu try.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisOrBaseExpected"> <source>Keyword 'this' or 'base' expected</source> <target state="translated">Očekávalo se klíčové slovo this nebo base.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlUnaryOperatorExpected"> <source>Overloadable unary operator expected</source> <target state="translated">Očekával se přetěžovatelný unární operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlBinaryOperatorExpected"> <source>Overloadable binary operator expected</source> <target state="translated">Očekával se přetěžovatelný binární operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_IntOverflow"> <source>Integral constant is too large</source> <target state="translated">Integrální konstanta je moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_EOFExpected"> <source>Type or namespace definition, or end-of-file expected</source> <target state="translated">Očekávala se definice typu nebo oboru názvů, nebo konec souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalDefinitionOrStatementExpected"> <source>Member definition, statement, or end-of-file expected</source> <target state="translated">Očekává se definice člena, příkaz nebo konec souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadEmbeddedStmt"> <source>Embedded statement cannot be a declaration or labeled statement</source> <target state="translated">Vloženým příkazem nemůže být deklarace ani příkaz s návěstím.</target> <note /> </trans-unit> <trans-unit id="ERR_PPDirectiveExpected"> <source>Preprocessor directive expected</source> <target state="translated">Očekávala se direktiva preprocesoru.</target> <note /> </trans-unit> <trans-unit id="ERR_EndOfPPLineExpected"> <source>Single-line comment or end-of-line expected</source> <target state="translated">Očekával se jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseParenExpected"> <source>) expected</source> <target state="translated">Očekává se ).</target> <note /> </trans-unit> <trans-unit id="ERR_EndifDirectiveExpected"> <source>#endif directive expected</source> <target state="translated">Očekávala se direktiva #endif.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedDirective"> <source>Unexpected preprocessor directive</source> <target state="translated">Neočekávaná direktiva preprocesoru</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorDirective"> <source>#error: '{0}'</source> <target state="translated">#error: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_WarningDirective"> <source>#warning: '{0}'</source> <target state="translated">#warning: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_WarningDirective_Title"> <source>#warning directive</source> <target state="translated">Direktiva #warning</target> <note /> </trans-unit> <trans-unit id="ERR_TypeExpected"> <source>Type expected</source> <target state="translated">Očekával se typ.</target> <note /> </trans-unit> <trans-unit id="ERR_PPDefFollowsToken"> <source>Cannot define/undefine preprocessor symbols after first token in file</source> <target state="translated">Po prvním tokenu v souboru nejde definovat symboly preprocesoru ani rušit jejich definice.</target> <note /> </trans-unit> <trans-unit id="ERR_PPReferenceFollowsToken"> <source>Cannot use #r after first token in file</source> <target state="translated">Nejde použít #r po prvním tokenu v souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_OpenEndedComment"> <source>End-of-file found, '*/' expected</source> <target state="translated">Našel se konec souboru. Očekával se řetězec */.</target> <note /> </trans-unit> <trans-unit id="ERR_Merge_conflict_marker_encountered"> <source>Merge conflict marker encountered</source> <target state="translated">Byla zjištěna značka konfliktu sloučení.</target> <note /> </trans-unit> <trans-unit id="ERR_NoRefOutWhenRefOnly"> <source>Do not use refout when using refonly.</source> <target state="translated">Když používáte refonly, nepoužívejte refout.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNetModuleOutputWhenRefOutOrRefOnly"> <source>Cannot compile net modules when using /refout or /refonly.</source> <target state="translated">Když se používá přepínač /refout nebo /refonly, nejde zkompilovat síťové moduly.</target> <note /> </trans-unit> <trans-unit id="ERR_OvlOperatorExpected"> <source>Overloadable operator expected</source> <target state="translated">Očekával se přetěžovatelný operátor.</target> <note /> </trans-unit> <trans-unit id="ERR_EndRegionDirectiveExpected"> <source>#endregion directive expected</source> <target state="translated">Očekávala se direktiva #endregion.</target> <note /> </trans-unit> <trans-unit id="ERR_UnterminatedStringLit"> <source>Unterminated string literal</source> <target state="translated">Neukončený řetězcový literál</target> <note /> </trans-unit> <trans-unit id="ERR_BadDirectivePlacement"> <source>Preprocessor directives must appear as the first non-whitespace character on a line</source> <target state="translated">Direktivy preprocesoru musí být uvedené jako první neprázdné znaky na řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_IdentifierExpectedKW"> <source>Identifier expected; '{1}' is a keyword</source> <target state="translated">Očekával se identifikátor; {1} je klíčové slovo.</target> <note /> </trans-unit> <trans-unit id="ERR_SemiOrLBraceExpected"> <source>{ or ; expected</source> <target state="translated">Očekávala se levá složená závorka ({) nebo středník (;).</target> <note /> </trans-unit> <trans-unit id="ERR_MultiTypeInDeclaration"> <source>Cannot use more than one type in a for, using, fixed, or declaration statement</source> <target state="translated">V příkazu deklarace for, using, fixed nebo or nejde použít více než jeden typ.</target> <note /> </trans-unit> <trans-unit id="ERR_AddOrRemoveExpected"> <source>An add or remove accessor expected</source> <target state="translated">Očekával se přistupující objekt add nebo remove.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedCharacter"> <source>Unexpected character '{0}'</source> <target state="translated">Neočekávaný znak {0}</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedToken"> <source>Unexpected token '{0}'</source> <target state="translated">Neočekávaný token {0}</target> <note /> </trans-unit> <trans-unit id="ERR_ProtectedInStatic"> <source>'{0}': static classes cannot contain protected members</source> <target state="translated">{0}: Statické třídy nemůžou obsahovat chráněné členy.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch"> <source>A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException.</source> <target state="translated">Předchozí klauzule catch už zachycuje všechny výjimky. Všechny vyvolané události, které nejsou výjimkami, budou zahrnuty do obálky třídy System.Runtime.CompilerServices.RuntimeWrappedException.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch_Title"> <source>A previous catch clause already catches all exceptions</source> <target state="translated">Předchozí klauzule catch už zachytává všechny výjimky.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreachableGeneralCatch_Description"> <source>This warning is caused when a catch() block has no specified exception type after a catch (System.Exception e) block. The warning advises that the catch() block will not catch any exceptions. A catch() block after a catch (System.Exception e) block can catch non-CLS exceptions if the RuntimeCompatibilityAttribute is set to false in the AssemblyInfo.cs file: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. If this attribute is not set explicitly to false, all thrown non-CLS exceptions are wrapped as Exceptions and the catch (System.Exception e) block catches them.</source> <target state="translated">Toto varování způsobuje, když blok catch() nemá žádný zadaný typ výjimky po bloku catch (System.Exception e). Varování informuje, že blok catch() nezachytí žádné výjimky. Blok catch() po bloku catch (System.Exception e) může zachytit výjimky, které nesouvisí se specifikací CLS, pokud je RuntimeCompatibilityAttribute nastavený na false v souboru AssemblyInfo.cs: [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)]. Pokud tento atribut není nastavený explicitně na false, všechny výjimky, které nesouvisí se specifikací CLS, se dostanou do balíčku Exceptions a blok catch (System.Exception e) je zachytí.</target> <note /> </trans-unit> <trans-unit id="ERR_IncrementLvalueExpected"> <source>The operand of an increment or decrement operator must be a variable, property or indexer</source> <target state="translated">Operandem operátoru přičtení nebo odečtení musí být proměnná, vlastnost nebo indexer.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMemberOrExtension"> <source>'{0}' does not contain a definition for '{1}' and no accessible extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)</source> <target state="translated">{0} neobsahuje definici pro {1} a nenašla se žádná dostupná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using nebo odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_NoSuchMemberOrExtensionNeedUsing"> <source>'{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive for '{2}'?)</source> <target state="translated">{0} neobsahuje definici pro {1} a nenašla se žádná metoda rozšíření {1}, která by přijímala první argument typu {0}. (Nechybí direktiva using pro {2}?)</target> <note /> </trans-unit> <trans-unit id="ERR_BadThisParam"> <source>Method '{0}' has a parameter modifier 'this' which is not on the first parameter</source> <target state="translated">Metoda {0} má modifikátor parametru this, který není na prvním parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParameterModifiers"> <source> The parameter modifier '{0}' cannot be used with '{1}'</source> <target state="translated"> Modifikátor parametru {0} nejde použít s modifikátorem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadTypeforThis"> <source>The first parameter of an extension method cannot be of type '{0}'</source> <target state="translated">První parametr metody rozšíření nesmí být typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamModThis"> <source>A parameter array cannot be used with 'this' modifier on an extension method</source> <target state="translated">V metodě rozšíření nejde použít pole parametrů s modifikátorem this.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExtensionMeth"> <source>Extension method must be static</source> <target state="translated">Metoda rozšíření musí být statická.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExtensionAgg"> <source>Extension method must be defined in a non-generic static class</source> <target state="translated">Metoda rozšíření musí být definovaná v neobecné statické třídě.</target> <note /> </trans-unit> <trans-unit id="ERR_DupParamMod"> <source>A parameter can only have one '{0}' modifier</source> <target state="translated">Parametr může mít jenom jeden modifikátor {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionMethodsDecl"> <source>Extension methods must be defined in a top level static class; {0} is a nested class</source> <target state="translated">Metody rozšíření musí být definované ve statické třídě nejvyšší úrovně; {0} je vnořená třída.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionAttrNotFound"> <source>Cannot define a new extension method because the compiler required type '{0}' cannot be found. Are you missing a reference to System.Core.dll?</source> <target state="translated">Nejde definovat novou metodu rozšíření, protože se nenašel vyžadovaný typ kompilátoru {0}. Nechybí odkaz na System.Core.dll?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitExtension"> <source>Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.</source> <target state="translated">Nepoužívejte System.Runtime.CompilerServices.ExtensionAttribute. Místo toho použijte klíčové slovo this.</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitDynamicAttr"> <source>Do not use 'System.Runtime.CompilerServices.DynamicAttribute'. Use the 'dynamic' keyword instead.</source> <target state="translated">Nepoužívejte System.Runtime.CompilerServices.DynamicAttribute. Místo toho použijte klíčové slovo dynamic.</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBaseCtor"> <source>The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.</source> <target state="translated">Volání konstruktoru je nutné volat dynamicky, což ale není možné, protože je součástí inicializátoru konstruktoru. Zvažte použití dynamických argumentů.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTypeExtDelegate"> <source>Extension method '{0}' defined on value type '{1}' cannot be used to create delegates</source> <target state="translated">Metoda rozšíření {0} definovaná v hodnotovém typu {1} se nedá použít k vytváření delegátů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgCount"> <source>No overload for method '{0}' takes {1} arguments</source> <target state="translated">Žádné přetížení pro metodu {0} nepřevezme tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgType"> <source>Argument {0}: cannot convert from '{1}' to '{2}'</source> <target state="translated">Argument {0}: Nejde převést z {1} na {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoSourceFile"> <source>Source file '{0}' could not be opened -- {1}</source> <target state="translated">Zdrojový soubor {0} nešel otevřít -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CantRefResource"> <source>Cannot link resource files when building a module</source> <target state="translated">Při sestavování modulu nejde propojit soubory prostředků.</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceNotUnique"> <source>Resource identifier '{0}' has already been used in this assembly</source> <target state="translated">Identifikátor prostředku {0} se už v tomto sestavení používá.</target> <note /> </trans-unit> <trans-unit id="ERR_ResourceFileNameNotUnique"> <source>Each linked resource and module must have a unique filename. Filename '{0}' is specified more than once in this assembly</source> <target state="translated">Každý propojený prostředek a modul musí mít jedinečný název souboru, ale {0} se v tomto sestavení objevuje víc než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_ImportNonAssembly"> <source>The referenced file '{0}' is not an assembly</source> <target state="translated">Odkazovaný soubor {0} není sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefLvalueExpected"> <source>A ref or out value must be an assignable variable</source> <target state="translated">Hodnotou Ref nebo Out musí být proměnná s možností přiřazení hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseInStaticMeth"> <source>Keyword 'base' is not available in a static method</source> <target state="translated">Klíčové slovo base není k dispozici uvnitř statické metody.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseInBadContext"> <source>Keyword 'base' is not available in the current context</source> <target state="translated">Klíčové slovo base není k dispozici v aktuálním kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_RbraceExpected"> <source>} expected</source> <target state="translated">Očekával se znak }.</target> <note /> </trans-unit> <trans-unit id="ERR_LbraceExpected"> <source>{ expected</source> <target state="translated">Očekával se znak {.</target> <note /> </trans-unit> <trans-unit id="ERR_InExpected"> <source>'in' expected</source> <target state="translated">'Očekávalo se klíčové slovo in.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocExpr"> <source>Invalid preprocessor expression</source> <target state="translated">Neplatný výraz preprocesoru</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidMemberDecl"> <source>Invalid token '{0}' in class, record, struct, or interface member declaration</source> <target state="translated">Neplatný token {0} v deklaraci člena rozhraní, třídy, záznamu nebo struktury</target> <note /> </trans-unit> <trans-unit id="ERR_MemberNeedsType"> <source>Method must have a return type</source> <target state="translated">Metoda musí mít typ vrácené hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBaseType"> <source>Invalid base type</source> <target state="translated">Neplatný základní typ</target> <note /> </trans-unit> <trans-unit id="WRN_EmptySwitch"> <source>Empty switch block</source> <target state="translated">Prázdný blok switch</target> <note /> </trans-unit> <trans-unit id="WRN_EmptySwitch_Title"> <source>Empty switch block</source> <target state="translated">Prázdný blok switch</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedEndTry"> <source>Expected catch or finally</source> <target state="translated">Očekávalo se klíčové slovo catch nebo finally.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidExprTerm"> <source>Invalid expression term '{0}'</source> <target state="translated">Neplatný výraz {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadNewExpr"> <source>A new expression requires an argument list or (), [], or {} after type</source> <target state="translated">Výraz new vyžaduje za typem seznam argumentů nebo (), [] nebo {}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoNamespacePrivate"> <source>Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected</source> <target state="translated">Elementy definované v názvovém prostoru nelze explicitně deklarovat jako private, protected, protected internal nebo private protected.</target> <note /> </trans-unit> <trans-unit id="ERR_BadVarDecl"> <source>Expected ; or = (cannot specify constructor arguments in declaration)</source> <target state="translated">Očekával se znak ; nebo = (v deklaraci nejde zadat argumenty konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_UsingAfterElements"> <source>A using clause must precede all other elements defined in the namespace except extern alias declarations</source> <target state="translated">Klauzule using musí předcházet všem ostatním prvkům definovaným v oboru názvů s výjimkou deklarací externích aliasů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBinOpArgs"> <source>Overloaded binary operator '{0}' takes two parameters</source> <target state="translated">Přetěžovaný binární operátor {0} používá dva parametry.</target> <note /> </trans-unit> <trans-unit id="ERR_BadUnOpArgs"> <source>Overloaded unary operator '{0}' takes one parameter</source> <target state="translated">Přetěžovaný unární operátor {0} převezme jeden parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_NoVoidParameter"> <source>Invalid parameter type 'void'</source> <target state="translated">Neplatný typ parametru void</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateAlias"> <source>The using alias '{0}' appeared previously in this namespace</source> <target state="translated">Alias using {0} se objevil dřív v tomto oboru názvů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadProtectedAccess"> <source>Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)</source> <target state="translated">K chráněnému členu {0} nejde přistupovat prostřednictvím kvalifikátoru typu {1}. Kvalifikátor musí být typu {2} (nebo musí být od tohoto typu odvozen).</target> <note /> </trans-unit> <trans-unit id="ERR_AddModuleAssembly"> <source>'{0}' cannot be added to this assembly because it already is an assembly</source> <target state="translated">{0} se nemůže přidat do tohoto sestavení, protože už to sestavení je.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogusProp2"> <source>Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'</source> <target state="translated">Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metody přistupujícího objektu {1} nebo {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BindToBogusProp1"> <source>Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'</source> <target state="translated">Vlastnost, indexer nebo událost {0} nejsou tímto jazykem podporované. Zkuste přímo volat metodu přistupujícího objektu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoVoidHere"> <source>Keyword 'void' cannot be used in this context</source> <target state="translated">Klíčové slovo void nejde v tomto kontextu použít.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexerNeedsParam"> <source>Indexers must have at least one parameter</source> <target state="translated">Indexery musí mít nejmíň jeden parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArraySyntax"> <source>Array type specifier, [], must appear before parameter name</source> <target state="translated">Před názvem parametru musí být uvedený specifikátor typu pole [].</target> <note /> </trans-unit> <trans-unit id="ERR_BadOperatorSyntax"> <source>Declaration is not valid; use '{0} operator &lt;dest-type&gt; (...' instead</source> <target state="translated">Deklarace není platná. Místo toho použijte: {0} operátor &lt;dest-type&gt; (...</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassNotFound"> <source>Could not find '{0}' specified for Main method</source> <target state="translated">Prvek {0} zadaný pro metodu Main se nenašel.</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassNotClass"> <source>'{0}' specified for Main method must be a non-generic class, record, struct, or interface</source> <target state="translated">Typ {0} zadaný pro metodu Main musí být neobecná třída, záznam, struktura nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMainInClass"> <source>'{0}' does not have a suitable static 'Main' method</source> <target state="translated">{0} nemá vhodnou statickou metodu Main.</target> <note /> </trans-unit> <trans-unit id="ERR_MainClassIsImport"> <source>Cannot use '{0}' for Main method because it is imported</source> <target state="translated">{0} nejde použít pro metodu Main, protože je importovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_OutputNeedsName"> <source>Outputs without source must have the /out option specified</source> <target state="translated">U výstupu bez zdroje musí být zadaný přepínač /out.</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndManifest"> <source>Conflicting options specified: Win32 resource file; Win32 manifest</source> <target state="translated">Jsou zadané konfliktní možnosti: soubor prostředků Win32, manifest Win32.</target> <note /> </trans-unit> <trans-unit id="ERR_CantHaveWin32ResAndIcon"> <source>Conflicting options specified: Win32 resource file; Win32 icon</source> <target state="translated">Jsou zadané konfliktní možnosti: soubor prostředků Win32, ikona Win32.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadResource"> <source>Error reading resource '{0}' -- '{1}'</source> <target state="translated">Chyba při čtení prostředku {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_DocFileGen"> <source>Error writing to XML documentation file: {0}</source> <target state="translated">Chyba při zápisu do souboru dokumentace XML: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseError"> <source>XML comment has badly formed XML -- '{0}'</source> <target state="translated">Komentáře XML má chybně vytvořený kód -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseError_Title"> <source>XML comment has badly formed XML</source> <target state="translated">Komentář XML má chybně vytvořený kód.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateParamTag"> <source>XML comment has a duplicate param tag for '{0}'</source> <target state="translated">Komentář XML má duplicitní značku param pro {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateParamTag_Title"> <source>XML comment has a duplicate param tag</source> <target state="translated">Komentář XML má duplicitní značku param.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamTag"> <source>XML comment has a param tag for '{0}', but there is no parameter by that name</source> <target state="translated">Komentář XML má značku param pro {0}, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamTag_Title"> <source>XML comment has a param tag, but there is no parameter by that name</source> <target state="translated">Komentář XML má značku param, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamRefTag"> <source>XML comment on '{1}' has a paramref tag for '{0}', but there is no parameter by that name</source> <target state="translated">Komentář XML u {1} má značku paramref pro {0}, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedParamRefTag_Title"> <source>XML comment has a paramref tag, but there is no parameter by that name</source> <target state="translated">Komentář XML má značku paramref, ale neexistuje parametr s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingParamTag"> <source>Parameter '{0}' has no matching param tag in the XML comment for '{1}' (but other parameters do)</source> <target state="translated">Parametr {0} nemá žádnou odpovídající značku param v komentáři XML pro {1} (ale jiné parametry ano).</target> <note /> </trans-unit> <trans-unit id="WRN_MissingParamTag_Title"> <source>Parameter has no matching param tag in the XML comment (but other parameters do)</source> <target state="translated">Parametr nemá odpovídající značku param v komentáři XML (na rozdíl od jiných parametrů).</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRef"> <source>XML comment has cref attribute '{0}' that could not be resolved</source> <target state="translated">Komentář XML má atribut cref {0}, který se nedal vyřešit.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRef_Title"> <source>XML comment has cref attribute that could not be resolved</source> <target state="translated">Komentář XML má atribut cref, který se nedal vyřešit.</target> <note /> </trans-unit> <trans-unit id="ERR_BadStackAllocExpr"> <source>A stackalloc expression requires [] after type</source> <target state="translated">Výraz stackalloc vyžaduje, aby za typem byly závorky [].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidLineNumber"> <source>The line number specified for #line directive is missing or invalid</source> <target state="translated">Číslo řádku zadané v direktivě #line se nenašlo nebo je neplatné.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingPPFile"> <source>Quoted file name, single-line comment or end-of-line expected</source> <target state="translated">Očekával se citovaný název souboru, jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedPPFile"> <source>Quoted file name expected</source> <target state="translated">Očekával se citovaný název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_ReferenceDirectiveOnlyAllowedInScripts"> <source>#r is only allowed in scripts</source> <target state="translated">#r je povolený jenom ve skriptech.</target> <note /> </trans-unit> <trans-unit id="ERR_ForEachMissingMember"> <source>foreach statement cannot operate on variables of type '{0}' because '{0}' does not contain a public instance or extension definition for '{1}'</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože {0} neobsahuje veřejnou definici instance nebo rozšíření pro {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefParamType"> <source>Invalid type for parameter {0} in XML comment cref attribute: '{1}'</source> <target state="translated">Neplatný typ pro parametr {0} v atributu cref komentáře XML: {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefParamType_Title"> <source>Invalid type for parameter in XML comment cref attribute</source> <target state="translated">Neplatný typ pro parametr v atributu cref komentáře XML.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefReturnType"> <source>Invalid return type in XML comment cref attribute</source> <target state="translated">Neplatný typ vrácené hodnoty v atributu cref komentáře XML</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefReturnType_Title"> <source>Invalid return type in XML comment cref attribute</source> <target state="translated">Neplatný typ vrácené hodnoty v atributu cref komentáře XML</target> <note /> </trans-unit> <trans-unit id="ERR_BadWin32Res"> <source>Error reading Win32 resources -- {0}</source> <target state="translated">Chyba při čtení prostředků Win32 -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefSyntax"> <source>XML comment has syntactically incorrect cref attribute '{0}'</source> <target state="translated">Komentář XML má syntakticky nesprávný atribut cref {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefSyntax_Title"> <source>XML comment has syntactically incorrect cref attribute</source> <target state="translated">Komentář XML má syntakticky nesprávný atribut cref.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModifierLocation"> <source>Member modifier '{0}' must precede the member type and name</source> <target state="translated">Modifikátor členu {0} musí předcházet jeho názvu a typu.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingArraySize"> <source>Array creation must have array size or array initializer</source> <target state="translated">Při vytváření pole musí být k dispozici velikost pole nebo inicializátor pole.</target> <note /> </trans-unit> <trans-unit id="WRN_UnprocessedXMLComment"> <source>XML comment is not placed on a valid language element</source> <target state="translated">Komentář XML není umístěný v platném prvku jazyka.</target> <note /> </trans-unit> <trans-unit id="WRN_UnprocessedXMLComment_Title"> <source>XML comment is not placed on a valid language element</source> <target state="translated">Komentář XML není umístěný v platném prvku jazyka.</target> <note /> </trans-unit> <trans-unit id="WRN_FailedInclude"> <source>Unable to include XML fragment '{1}' of file '{0}' -- {2}</source> <target state="translated">Nejde zahrnout fragment XML {1} ze souboru {0} -- {2}</target> <note /> </trans-unit> <trans-unit id="WRN_FailedInclude_Title"> <source>Unable to include XML fragment</source> <target state="translated">Nejde zahrnout fragment XML.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidInclude"> <source>Invalid XML include element -- {0}</source> <target state="translated">Neplatný prvek direktivy include XML -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidInclude_Title"> <source>Invalid XML include element</source> <target state="translated">Neplatný prvek direktivy include XML</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment"> <source>Missing XML comment for publicly visible type or member '{0}'</source> <target state="translated">Komentář XML pro veřejně viditelný typ nebo člen {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment_Title"> <source>Missing XML comment for publicly visible type or member</source> <target state="translated">Komentář XML pro veřejně viditelný typ nebo člen se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingXMLComment_Description"> <source>The /doc compiler option was specified, but one or more constructs did not have comments.</source> <target state="translated">Byla zadaná možnost kompilátoru /doc, ale nejmíň jedna konstrukce neměla komentáře.</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseIncludeError"> <source>Badly formed XML in included comments file -- '{0}'</source> <target state="translated">Chybně vytvořený kód XML v zahrnutém souboru komentáře -- {0}</target> <note /> </trans-unit> <trans-unit id="WRN_XMLParseIncludeError_Title"> <source>Badly formed XML in included comments file</source> <target state="translated">Chybně vytvořený kód XML v zahrnutém souboru komentářů</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelArgCount"> <source>Delegate '{0}' does not take {1} arguments</source> <target state="translated">Delegát {0} nepřevezme tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedSemicolon"> <source>Semicolon after method or accessor block is not valid</source> <target state="translated">Středník není platný za metodou nebo blokem přistupujícího objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodReturnCantBeRefAny"> <source>The return type of a method, delegate, or function pointer cannot be '{0}'</source> <target state="translated">Návratový typ metody, delegáta nebo ukazatele na funkci nemůže být {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_CompileCancelled"> <source>Compilation cancelled by user</source> <target state="translated">Kompilaci zrušil uživatel.</target> <note /> </trans-unit> <trans-unit id="ERR_MethodArgCantBeRefAny"> <source>Cannot make reference to variable of type '{0}'</source> <target state="translated">Nejde vytvořit odkaz na proměnnou typu {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocal"> <source>Cannot assign to '{0}' because it is read-only</source> <target state="translated">K položce nejde přiřadit {0}, protože je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocal"> <source>Cannot use '{0}' as a ref or out value because it is read-only</source> <target state="translated">{0} nejde použít jako hodnotu Ref nebo Out, protože je jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_CantUseRequiredAttribute"> <source>The RequiredAttribute attribute is not permitted on C# types</source> <target state="translated">Atribut RequiredAttribute není povolený pro typy C#.</target> <note /> </trans-unit> <trans-unit id="ERR_NoModifiersOnAccessor"> <source>Modifiers cannot be placed on event accessor declarations</source> <target state="translated">Modifikátory nejde umístit do deklarace přistupujícího objektu události.</target> <note /> </trans-unit> <trans-unit id="ERR_ParamsCantBeWithModifier"> <source>The params parameter cannot be declared as {0}</source> <target state="translated">Parametr params nejde deklarovat jako {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnNotLValue"> <source>Cannot modify the return value of '{0}' because it is not a variable</source> <target state="translated">Vrácenou hodnotu {0} nejde změnit, protože se nejedná o proměnnou.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingCoClass"> <source>The managed coclass wrapper class '{0}' for interface '{1}' cannot be found (are you missing an assembly reference?)</source> <target state="translated">Spravovaná třída obálky coclass {0} pro rozhraní {1} se nedá najít. (Nechybí odkaz na sestavení?)</target> <note /> </trans-unit> <trans-unit id="ERR_AmbiguousAttribute"> <source>'{0}' is ambiguous between '{1}' and '{2}'. Either use '@{0}' or explicitly include the 'Attribute' suffix.</source> <target state="needs-review-translation">{0} je nejednoznačné mezi {1} a {2}; použijte buď @{0}, nebo {0}Attribute.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgExtraRef"> <source>Argument {0} may not be passed with the '{1}' keyword</source> <target state="translated">Argument {0} se nesmí předávat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource"> <source>Option '{0}' overrides attribute '{1}' given in a source file or added module</source> <target state="translated">Možnost {0} přepíše atribut {1} zadaný ve zdrojovém souboru nebo přidaném modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource_Title"> <source>Option overrides attribute given in a source file or added module</source> <target state="translated">Možnost přepíše atribut zadaný ve zdrojovém souboru nebo přidaném modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CmdOptionConflictsSource_Description"> <source>This warning occurs if the assembly attributes AssemblyKeyFileAttribute or AssemblyKeyNameAttribute found in source conflict with the /keyfile or /keycontainer command line option or key file name or key container specified in the Project Properties.</source> <target state="translated">Toto varování se objeví, pokud jsou atributy sestavení AssemblyKeyFileAttribute nebo AssemblyKeyNameAttribute nacházející se ve zdroji v konfliktu s parametrem příkazového řádku /keyfile nebo /keycontainer nebo názvem souboru klíče nebo kontejnerem klíčů zadaným ve vlastnostech projektu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCompatMode"> <source>Invalid option '{0}' for /langversion. Use '/langversion:?' to list supported values.</source> <target state="translated">Neplatný parametr {0} pro /langversion. Podporované hodnoty vypíšete pomocí /langversion:?.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateOnConditional"> <source>Cannot create delegate with '{0}' because it or a method it overrides has a Conditional attribute</source> <target state="translated">Delegáta s {0} nejde vytvořit, protože ten nebo metoda, kterou přepisuje, má atribut Conditional.</target> <note /> </trans-unit> <trans-unit id="ERR_CantMakeTempFile"> <source>Cannot create temporary file -- {0}</source> <target state="translated">Nedá se vytvořit dočasný soubor -- {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgRef"> <source>Argument {0} must be passed with the '{1}' keyword</source> <target state="translated">Argument {0} se musí předávat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_YieldInAnonMeth"> <source>The yield statement cannot be used inside an anonymous method or lambda expression</source> <target state="translated">Příkaz yield nejde používat uvnitř anonymních metod a výrazů lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_ReturnInIterator"> <source>Cannot return a value from an iterator. Use the yield return statement to return a value, or yield break to end the iteration.</source> <target state="translated">Nejde vrátit hodnotu z iterátoru. K vrácení hodnoty použijte příkaz yield return. K ukončení opakování použijte příkaz yield break.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorArgType"> <source>Iterators cannot have ref, in or out parameters</source> <target state="translated">U iterátorů nejde používat parametry ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturn"> <source>The body of '{0}' cannot be an iterator block because '{1}' is not an iterator interface type</source> <target state="translated">Tělo {0} nemůže být blok iterátoru, protože {1} není typ rozhraní iterátoru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInFinally"> <source>Cannot yield in the body of a finally clause</source> <target state="translated">V těle klauzule finally nejde používat příkaz yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInTryOfCatch"> <source>Cannot yield a value in the body of a try block with a catch clause</source> <target state="translated">V těle bloku try s klauzulí catch nejde uvést hodnotu příkazu yield.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyYield"> <source>Expression expected after yield return</source> <target state="translated">Po příkazu yield return se očekával výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonDelegateCantUse"> <source>Cannot use ref, out, or in parameter '{0}' inside an anonymous method, lambda expression, query expression, or local function</source> <target state="translated">Parametr ref, out nebo in {0} nejde použít uvnitř anonymní metody, výrazu lambda, výrazu dotazu nebo lokální funkce.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalInnerUnsafe"> <source>Unsafe code may not appear in iterators</source> <target state="translated">Iterátory nesmí obsahovat nezabezpečený kód.</target> <note /> </trans-unit> <trans-unit id="ERR_BadYieldInCatch"> <source>Cannot yield a value in the body of a catch clause</source> <target state="translated">V těle klauzule catch nejde použít hodnotu získanou příkazem yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDelegateLeave"> <source>Control cannot leave the body of an anonymous method or lambda expression</source> <target state="translated">Ovládací prvek nemůže opustit tělo anonymní metody nebo výrazu lambda.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPragma"> <source>Unrecognized #pragma directive</source> <target state="translated">Nerozpoznaná direktiva #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPragma_Title"> <source>Unrecognized #pragma directive</source> <target state="translated">Nerozpoznaná direktiva #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPWarning"> <source>Expected 'disable' or 'restore'</source> <target state="translated">Očekávala se hodnota disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPWarning_Title"> <source>Expected 'disable' or 'restore' after #pragma warning</source> <target state="translated">Po varování #pragma se očekávala hodnota disable nebo restore.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRestoreNumber"> <source>Cannot restore warning 'CS{0}' because it was disabled globally</source> <target state="translated">Nejde obnovit varování CS{0}, protože je globálně zakázané.</target> <note /> </trans-unit> <trans-unit id="WRN_BadRestoreNumber_Title"> <source>Cannot restore warning because it was disabled globally</source> <target state="translated">Nejde obnovit varování, protože bylo globálně zakázané.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsIterator"> <source>__arglist is not allowed in the parameter list of iterators</source> <target state="translated">Parametr __arglist není povolený v seznamu parametrů iterátorů.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeIteratorArgType"> <source>Iterators cannot have unsafe parameters or yield types</source> <target state="translated">U iterátorů nejde používat nezabezpečené parametry nebo typy yield.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCoClassSig"> <source>The managed coclass wrapper class signature '{0}' for interface '{1}' is not a valid class name signature</source> <target state="translated">Podpis spravované třídy obálky coclass {0} pro rozhraní {1} není platný podpis názvu třídy.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleIEnumOfT"> <source>foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation</source> <target state="translated">Příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedDimsRequired"> <source>A fixed size buffer field must have the array size specifier after the field name</source> <target state="translated">Pole vyrovnávací paměti s pevnou velikostí musí mít za názvem pole uvedený specifikátor velikosti pole.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNotInStruct"> <source>Fixed size buffer fields may only be members of structs</source> <target state="translated">Pole vyrovnávací paměti pevné velikosti můžou být jenom členy struktur.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousReturnExpected"> <source>Not all code paths return a value in {0} of type '{1}'</source> <target state="translated">Ne všechny cesty kódu vracejí hodnotu v {0} typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_NonECMAFeature"> <source>Feature '{0}' is not part of the standardized ISO C# language specification, and may not be accepted by other compilers</source> <target state="translated">Funkce {0} není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech</target> <note /> </trans-unit> <trans-unit id="WRN_NonECMAFeature_Title"> <source>Feature is not part of the standardized ISO C# language specification, and may not be accepted by other compilers</source> <target state="translated">Funkce není součástí standardizované specifikace ISO jazyka C# a možná ji nepůjde použít v ostatních kompilátorech</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedVerbatimLiteral"> <source>Keyword, identifier, or string expected after verbatim specifier: @</source> <target state="translated">Po specifikátoru verbatim se očekávalo klíčové slovo, identifikátor nebo řetězec: @</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonly"> <source>A readonly field cannot be used as a ref or out value (except in a constructor)</source> <target state="translated">Pole určené jen pro čtení nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonly2"> <source>Members of readonly field '{0}' cannot be used as a ref or out value (except in a constructor)</source> <target state="translated">Členy pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nachází uvnitř konstruktoru). </target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonly"> <source>A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)</source> <target state="translated">Do pole jen pro čtení není možné přiřazovat hodnoty (kromě případu, kdy je v konstruktoru nebo v metodě setter jen pro inicializaci typu, ve kterém je pole definované, nebo v inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonly2"> <source>Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)</source> <target state="translated">Členy pole jen pro čtení {0} nejde měnit (kromě případu, kdy se nacházejí uvnitř konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyNotField"> <source>Cannot use {0} '{1}' as a ref or out value because it is a readonly variable</source> <target state="translated">Nejde použít {0} {1} jako hodnotu ref nebo out, protože je to proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyNotField2"> <source>Members of {0} '{1}' cannot be used as a ref or out value because it is a readonly variable</source> <target state="translated">Členy {0} {1} nejde použít jako hodnotu ref nebo out, protože je to proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignReadonlyNotField"> <source>Cannot assign to {0} '{1}' because it is a readonly variable</source> <target state="translated">Nejde přiřadit k položce {0} {1}, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssignReadonlyNotField2"> <source>Cannot assign to a member of {0} '{1}' because it is a readonly variable</source> <target state="translated">Nejde přiřadit členovi {0} {1}, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyNotField"> <source>Cannot return {0} '{1}' by writable reference because it is a readonly variable</source> <target state="translated">Nejde vrátit {0} {1} zapisovatelným odkazem, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyNotField2"> <source>Members of {0} '{1}' cannot be returned by writable reference because it is a readonly variable</source> <target state="translated">Členy {0} {1} nejde vrátit zapisovatelným odkazem, protože to je proměnná jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)</source> <target state="translated">Pole statických polí jen pro čtení {0} nejde přiřadit (kromě případu, kdy se nacházejí uvnitř statického konstruktoru nebo inicializátoru proměnné).</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be used as a ref or out value (except in a static constructor)</source> <target state="translated">Pole statického pole jen pro čtení {0} nejde použít jako hodnotu Ref nebo Out (kromě případu, kdy se nacházejí uvnitř statického konstruktoru).</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocal2Cause"> <source>Cannot modify members of '{0}' because it is a '{1}'</source> <target state="translated">Členy z {0} nejde upravit, protože jde o {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocal2Cause"> <source>Cannot use fields of '{0}' as a ref or out value because it is a '{1}'</source> <target state="translated">Pole elementu {0} nejde použít jako hodnotu Ref nebo Out, protože je {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_AssgReadonlyLocalCause"> <source>Cannot assign to '{0}' because it is a '{1}'</source> <target state="translated">K položce nejde přiřadit {0}, protože je typu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReadonlyLocalCause"> <source>Cannot use '{0}' as a ref or out value because it is a '{1}'</source> <target state="translated">{0} nejde použít jako hodnotu Ref nebo Out, protože je {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride"> <source>{0}. See also error CS{1}.</source> <target state="translated">{0}. Viz taky chyba CS{1}.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride_Title"> <source>Warning is overriding an error</source> <target state="translated">Varování přepisuje chybu.</target> <note /> </trans-unit> <trans-unit id="WRN_ErrorOverride_Description"> <source>The compiler emits this warning when it overrides an error with a warning. For information about the problem, search for the error code mentioned.</source> <target state="translated">Kompilátor vydá toto varování, když přepíše chybu varováním. Informace o tomto problému vyhledejte podle uvedeného kódu chyby.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonMethToNonDel"> <source>Cannot convert {0} to type '{1}' because it is not a delegate type</source> <target state="translated">{0} nejde převést na typ {1}, protože to není typ delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethParams"> <source>Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types</source> <target state="translated">{0} nejde převést na typ {1}, protože typy parametrů se neshodují s typy parametrů delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethReturns"> <source>Cannot convert {0} to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type</source> <target state="translated">{0} nejde převést na zamýšlený typ delegáta, protože některé z návratových typů v bloku nejsou implicitně převeditelné na návratový typ tohoto delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturnExpression"> <source>Since this is an async method, the return expression must be of type '{0}' rather than 'Task&lt;{0}&gt;'</source> <target state="translated">Protože se jedná o asynchronní metodu, vrácený výraz musí být typu {0} a ne typu Task&lt;{0}&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAsyncAnonFuncReturns"> <source>Cannot convert async {0} to delegate type '{1}'. An async {0} may return void, Task or Task&lt;T&gt;, none of which are convertible to '{1}'.</source> <target state="translated">Asynchronní metodu {0} nejde převést na typ delegáta {1}. Asynchronní metoda {0} může vracet hodnoty typu void, Task nebo Task&lt; T&gt; , z nichž žádnou nejde převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalFixedType"> <source>Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double</source> <target state="translated">Typ vyrovnávací paměti pevné velikosti musí být následující: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float nebo double.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedOverflow"> <source>Fixed size buffer of length {0} and type '{1}' is too big</source> <target state="translated">Vyrovnávací paměť pevné velikosti s délkou {0} a typem {1} je moc velká.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFixedArraySize"> <source>Fixed size buffers must have a length greater than zero</source> <target state="translated">Vyrovnávací paměti pevné velikosti mají délku větší než nula.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedBufferNotFixed"> <source>You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement.</source> <target state="translated">Vyrovnávací paměti pevné velikosti obsažené ve volném výrazu nejde používat. Použijte příkaz fixed.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributeNotOnAccessor"> <source>Attribute '{0}' is not valid on property or event accessors. It is only valid on '{1}' declarations.</source> <target state="translated">Atribut {0} není platný pro přistupující objekty vlastnosti nebo události. Je platný jenom pro deklarace {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSearchPathDir"> <source>Invalid search path '{0}' specified in '{1}' -- '{2}'</source> <target state="translated">Neplatná vyhledávací cesta {0} zadaná v {1} -- {2}</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidSearchPathDir_Title"> <source>Invalid search path specified</source> <target state="translated">Byla zadaná neplatná vyhledávací cesta.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalVarArgs"> <source>__arglist is not valid in this context</source> <target state="translated">Klíčové slovo __arglist není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalParams"> <source>params is not valid in this context</source> <target state="translated">Klíčové slovo params není v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModifiersOnNamespace"> <source>A namespace declaration cannot have modifiers or attributes</source> <target state="translated">Deklarace oboru názvů nemůže mít modifikátory ani atributy.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPlatformType"> <source>Invalid option '{0}' for /platform; must be anycpu, x86, Itanium, arm, arm64 or x64</source> <target state="translated">Neplatná možnost {0} pro /platform. Musí být anycpu, x86, Itanium, arm, arm64 nebo x64.</target> <note /> </trans-unit> <trans-unit id="ERR_ThisStructNotInAnonMeth"> <source>Anonymous methods, lambda expressions, query expressions, and local functions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression, query expression, or local function and using the local instead.</source> <target state="translated">Anonymní metody, výrazy lambda, výrazy dotazu a místní funkce uvnitř struktur nemají přístup ke členům instance this. Jako náhradu zkopírujte objekt this do lokální proměnné vně anonymní metody, výrazu lambda, výrazu dotazu nebo místní funkce a použijte tuto lokální proměnnou.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIDisp"> <source>'{0}': type used in a using statement must be implicitly convertible to 'System.IDisposable'.</source> <target state="translated">{0}: Typ použitý v příkazu using musí být implicitně převeditelný na System.IDisposable.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamRef"> <source>Parameter {0} must be declared with the '{1}' keyword</source> <target state="translated">Parametr {0} se musí deklarovat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamExtraRef"> <source>Parameter {0} should not be declared with the '{1}' keyword</source> <target state="translated">Parametr {0} by se neměl deklarovat s klíčovým slovem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadParamType"> <source>Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}'</source> <target state="translated">Parametr {0} se deklaruje jako typ {1}{2}, ale mělo by jít o {3}{4}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadExternIdentifier"> <source>Invalid extern alias for '/reference'; '{0}' is not a valid identifier</source> <target state="translated">Neplatný externí alias pro parametr /reference; {0} je neplatný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasMissingFile"> <source>Invalid reference alias option: '{0}=' -- missing filename</source> <target state="translated">Neplatný parametr aliasu odkazu: {0}= – nenašel se název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalExternAlias"> <source>You cannot redefine the global extern alias</source> <target state="translated">Nejde předefinovat globální externí alias.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingTypeInSource"> <source>Reference to type '{0}' claims it is defined in this assembly, but it is not defined in source or any added modules</source> <target state="translated">Odkaz na typ {0} se deklaruje jako definovaný v tomto sestavení, ale není definovaný ve zdroji ani v žádných přidaných modulech.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingTypeInAssembly"> <source>Reference to type '{0}' claims it is defined in '{1}', but it could not be found</source> <target state="translated">Odkaz na typ {0} se deklaruje jako definovaný v rámci {1}, ale nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes"> <source>The predefined type '{0}' is defined in multiple assemblies in the global alias; using definition from '{1}'</source> <target state="translated">Předdefinovaný typ {0} je definovaný ve více sestaveních v globálním aliasu; použije se definice z {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes_Title"> <source>Predefined type is defined in multiple assemblies in the global alias</source> <target state="translated">Předdefinovaný typ je definovaný ve více sestaveních v globálním aliasu.</target> <note /> </trans-unit> <trans-unit id="WRN_MultiplePredefTypes_Description"> <source>This error occurs when a predefined system type such as System.Int32 is found in two assemblies. One way this can happen is if you are referencing mscorlib or System.Runtime.dll from two different places, such as trying to run two versions of the .NET Framework side-by-side.</source> <target state="translated">K této chybě dojde, když se předdefinovaný systémový typ, jako je System.Int32, nachází ve dvou sestaveních. Jedna z možností, jak se to může stát, je, že odkazujete na mscorlib nebo System.Runtime.dll, ze dvou různých míst, například při pokusu spustit dvě verze .NET Framework vedle sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalCantBeFixedAndHoisted"> <source>Local '{0}' or its members cannot have their address taken and be used inside an anonymous method or lambda expression</source> <target state="translated">Adresu místní proměnné {0} ani jejích členů nejde vzít a použít uvnitř anonymní metody nebo lambda výrazu.</target> <note /> </trans-unit> <trans-unit id="WRN_TooManyLinesForDebugger"> <source>Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect</source> <target state="translated">U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné.</target> <note /> </trans-unit> <trans-unit id="WRN_TooManyLinesForDebugger_Title"> <source>Source file has exceeded the limit of 16,707,565 lines representable in the PDB; debug information will be incorrect</source> <target state="translated">U zdrojového souboru se překročil limit 16 707 565 řádků, které může soubor PDB obsahovat. Ladicí informace budou nesprávné.</target> <note /> </trans-unit> <trans-unit id="ERR_CantConvAnonMethNoParams"> <source>Cannot convert anonymous method block without a parameter list to delegate type '{0}' because it has one or more out parameters</source> <target state="translated">Blok anonymní metody bez seznamu parametrů nejde převést na typ delegáta {0}, protože má nejmíň jeden parametr out.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalOnNonAttributeClass"> <source>Attribute '{0}' is only valid on methods or attribute classes</source> <target state="translated">Atribut {0} je platný jenom pro metody nebo třídy atributů.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField"> <source>Accessing a member on '{0}' may cause a runtime exception because it is a field of a marshal-by-reference class</source> <target state="translated">Přístup ke členovi na {0} může způsobit výjimku za běhu, protože se jedná o pole třídy marshal-by-reference.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField_Title"> <source>Accessing a member on a field of a marshal-by-reference class may cause a runtime exception</source> <target state="translated">Přístup ke členovi v poli třídy marshal-by-reference může způsobit běhovou výjimku.</target> <note /> </trans-unit> <trans-unit id="WRN_CallOnNonAgileField_Description"> <source>This warning occurs when you try to call a method, property, or indexer on a member of a class that derives from MarshalByRefObject, and the member is a value type. Objects that inherit from MarshalByRefObject are typically intended to be marshaled by reference across an application domain. If any code ever attempts to directly access the value-type member of such an object across an application domain, a runtime exception will occur. To resolve the warning, first copy the member into a local variable and call the method on that variable.</source> <target state="translated">Toto varování se vyskytne, když se pokusíte volat metodu, vlastnost nebo indexer u členu třídy, která se odvozuje z objektu MarshalByRefObject, a tento člen je typu hodnota. Objekty, které dědí z objektu MarshalByRefObject, jsou obvykle zamýšlené tak, že se budou zařazovat podle odkazů v aplikační doméně. Pokud se nějaký kód někdy pokusí o přímý přístup ke členu typu hodnota takového objektu někde v aplikační doméně, dojde k výjimce běhu modulu runtime. Pokud chcete vyřešit toto varování, zkopírujte nejdřív člen do místní proměnné a pak u ní vyvolejte uvedenou metodu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber"> <source>'{0}' is not a valid warning number</source> <target state="translated">{0} není platné číslo upozornění.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber_Title"> <source>Not a valid warning number</source> <target state="translated">Není platné číslo varování.</target> <note /> </trans-unit> <trans-unit id="WRN_BadWarningNumber_Description"> <source>A number that was passed to the #pragma warning preprocessor directive was not a valid warning number. Verify that the number represents a warning, not an error.</source> <target state="translated">Číslo, které bylo předané do direktivy preprocesoru varování #pragma, nepředstavovalo platné číslo varování. Ověřte, že číslo představuje varování, ne chybu.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidNumber"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidNumber_Title"> <source>Invalid number</source> <target state="translated">Neplatné číslo</target> <note /> </trans-unit> <trans-unit id="WRN_FileNameTooLong"> <source>Invalid filename specified for preprocessor directive. Filename is too long or not a valid filename.</source> <target state="translated">V direktivě preprocesoru je uvedený neplatný název souboru. Název souboru je moc dlouhý nebo se nejedná o platný název souboru.</target> <note /> </trans-unit> <trans-unit id="WRN_FileNameTooLong_Title"> <source>Invalid filename specified for preprocessor directive</source> <target state="translated">Byl zadaný neplatný název souboru pro direktivu preprocesoru.</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPChecksum"> <source>Invalid #pragma checksum syntax; should be #pragma checksum "filename" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..."</source> <target state="translated">Syntaxe #pragma checksum není platná. Správná syntaxe: #pragma checksum "název_souboru" "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}" "XXXX..."</target> <note /> </trans-unit> <trans-unit id="WRN_IllegalPPChecksum_Title"> <source>Invalid #pragma checksum syntax</source> <target state="translated">Neplatná syntaxe kontrolního součtu #pragma</target> <note /> </trans-unit> <trans-unit id="WRN_EndOfPPLineExpected"> <source>Single-line comment or end-of-line expected</source> <target state="translated">Očekával se jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="WRN_EndOfPPLineExpected_Title"> <source>Single-line comment or end-of-line expected after #pragma directive</source> <target state="translated">Po direktivě #pragma se očekával jednořádkový komentář nebo konec řádku.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingChecksum"> <source>Different checksum values given for '{0}'</source> <target state="translated">Pro {0} jsou zadané různé hodnoty kontrolního součtu.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingChecksum_Title"> <source>Different #pragma checksum values given</source> <target state="translated">Jsou zadané různé hodnoty kontrolního součtu direktivy #pragma.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName"> <source>Assembly reference '{0}' is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení {0} je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Title"> <source>Assembly reference is invalid and cannot be resolved</source> <target state="translated">Odkaz na sestavení je neplatný a nedá se vyhodnotit.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidAssemblyName_Description"> <source>This warning indicates that an attribute, such as InternalsVisibleToAttribute, was not specified correctly.</source> <target state="translated">Toto varování indikuje, že některý atribut, třeba InternalsVisibleToAttribute, nebyl zadaný správně.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin"> <source>Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy</source> <target state="translated">Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin_Title"> <source>Assuming assembly reference matches identity</source> <target state="translated">Předpokládá se, že odkaz na sestavení odpovídá identitě.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceMajMin_Description"> <source>The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly.</source> <target state="translated">Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev"> <source>Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy</source> <target state="translated">Předpokládá se, že odkaz na sestavení {0}, který používá {1}, odpovídá identitě {2} pro {3}. Možná budete muset zadat zásady pro běh.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev_Title"> <source>Assuming assembly reference matches identity</source> <target state="translated">Předpokládá se, že odkaz na sestavení odpovídá identitě.</target> <note /> </trans-unit> <trans-unit id="WRN_UnifyReferenceBldRev_Description"> <source>The two assemblies differ in release and/or version number. For unification to occur, you must specify directives in the application's .config file, and you must provide the correct strong name of an assembly.</source> <target state="translated">Tato dvě sestavení se liší číslem vydání nebo verze. Aby mohlo proběhnout sjednocení, musíte zadat direktivy v souboru .config aplikace a musíte poskytnout správný silný název sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImport"> <source>Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.</source> <target state="translated">Naimportovalo se víc sestavení s ekvivalentní identitou: {0} a {1}. Odeberte jeden z duplicitních odkazů.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateImportSimple"> <source>An assembly with the same simple name '{0}' has already been imported. Try removing one of the references (e.g. '{1}') or sign them to enable side-by-side.</source> <target state="translated">Už se naimportovalo sestavení se stejným jednoduchým názvem {0}. Zkuste odebrat jeden z odkazů (např. {1}) nebo je podepište, aby mohly fungovat vedle sebe.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblyMatchBadVersion"> <source>Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}'</source> <target state="translated">Sestavení {0} s identitou {1} používá {2} s vyšší verzí, než jakou má odkazované sestavení {3} s identitou {4}.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedNeedsLvalue"> <source>Fixed size buffers can only be accessed through locals or fields</source> <target state="translated">K vyrovnávacím pamětem s pevnou velikostí jde získat přístup jenom prostřednictvím lokálních proměnných nebo polí.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateTypeParamTag"> <source>XML comment has a duplicate typeparam tag for '{0}'</source> <target state="translated">Komentář XML má duplicitní značku typeparam pro {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_DuplicateTypeParamTag_Title"> <source>XML comment has a duplicate typeparam tag</source> <target state="translated">Komentář XML má duplicitní značku typeparam.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamTag"> <source>XML comment has a typeparam tag for '{0}', but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparam pro {0}, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamTag_Title"> <source>XML comment has a typeparam tag, but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparam, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamRefTag"> <source>XML comment on '{1}' has a typeparamref tag for '{0}', but there is no type parameter by that name</source> <target state="translated">Komentář XML u {1} má značku typeparamref pro {0}, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_UnmatchedTypeParamRefTag_Title"> <source>XML comment has a typeparamref tag, but there is no type parameter by that name</source> <target state="translated">Komentář XML má značku typeparamref, ale neexistuje parametr typu s tímto názvem.</target> <note /> </trans-unit> <trans-unit id="WRN_MissingTypeParamTag"> <source>Type parameter '{0}' has no matching typeparam tag in the XML comment on '{1}' (but other type parameters do)</source> <target state="translated">Parametr typu {0} nemá žádnou odpovídající značku typeparam v komentáři XML na {1} (ale jiné parametry typu ano).</target> <note /> </trans-unit> <trans-unit id="WRN_MissingTypeParamTag_Title"> <source>Type parameter has no matching typeparam tag in the XML comment (but other type parameters do)</source> <target state="translated">Parametr typu nemá odpovídající značku typeparam v komentáři XML (na rozdíl od jiných parametrů typu).</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeTypeOnOverride"> <source>'{0}': type must be '{2}' to match overridden member '{1}'</source> <target state="translated">{0}: Typ musí být {2}, aby odpovídal přepsanému členu {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DoNotUseFixedBufferAttr"> <source>Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead.</source> <target state="translated">Nepoužívejte atribut System.Runtime.CompilerServices.FixedBuffer. Místo něj použijte modifikátor pole fixed.</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToSelf"> <source>Assignment made to same variable; did you mean to assign something else?</source> <target state="translated">Přiřazení proběhlo u stejné proměnné. Měli jste v úmyslu jiné přiřazení?</target> <note /> </trans-unit> <trans-unit id="WRN_AssignmentToSelf_Title"> <source>Assignment made to same variable</source> <target state="translated">Přiřazení provedené u stejné proměnné</target> <note /> </trans-unit> <trans-unit id="WRN_ComparisonToSelf"> <source>Comparison made to same variable; did you mean to compare something else?</source> <target state="translated">Porovnání proběhlo u stejné proměnné. Měli jste v úmyslu jiné porovnání?</target> <note /> </trans-unit> <trans-unit id="WRN_ComparisonToSelf_Title"> <source>Comparison made to same variable</source> <target state="translated">Porovnání provedené u stejné proměnné</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenWin32Res"> <source>Error opening Win32 resource file '{0}' -- '{1}'</source> <target state="translated">Chyba při otevírání souboru prostředků Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="WRN_DotOnDefault"> <source>Expression will always cause a System.NullReferenceException because the default value of '{0}' is null</source> <target state="translated">Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota {0} je null.</target> <note /> </trans-unit> <trans-unit id="WRN_DotOnDefault_Title"> <source>Expression will always cause a System.NullReferenceException because the type's default value is null</source> <target state="translated">Výraz způsobí výjimku System.NullReferenceException, protože výchozí hodnota pro typ je null.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMultipleInheritance"> <source>Class '{0}' cannot have multiple base classes: '{1}' and '{2}'</source> <target state="translated">Třída {0} nemůže mít víc základních tříd: {1} a {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_BaseClassMustBeFirst"> <source>Base class '{0}' must come before any interfaces</source> <target state="translated">Základní třída {0} musí předcházet všem rozhraním.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefTypeVar"> <source>XML comment has cref attribute '{0}' that refers to a type parameter</source> <target state="translated">Komentář XML má atribut cref {0}, který odkazuje na parametr typu.</target> <note /> </trans-unit> <trans-unit id="WRN_BadXMLRefTypeVar_Title"> <source>XML comment has cref attribute that refers to a type parameter</source> <target state="translated">Komentář XML má atribut cref, který odkazuje na parametr typu.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblyBadArgs"> <source>Friend assembly reference '{0}' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified.</source> <target state="translated">Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo nesmí být zadaná verze, jazykové prostředí, token veřejného klíče ani architektura procesoru.</target> <note /> </trans-unit> <trans-unit id="ERR_FriendAssemblySNReq"> <source>Friend assembly reference '{0}' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations.</source> <target state="translated">Odkaz na sestavení {0} typu Friend je neplatný. V deklaracích InternalsVisibleTo musí být u podepsaných sestavení se silným názvem uvedený veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_DelegateOnNullable"> <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable&lt;T&gt;'</source> <target state="translated">Nejde vytvořit vazbu delegáta s {0}, protože je členem struktury System.Nullable&lt;T&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCtorArgCount"> <source>'{0}' does not contain a constructor that takes {1} arguments</source> <target state="translated">{0} neobsahuje konstruktor, který přebírá tento počet argumentů: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalAttributesNotFirst"> <source>Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations</source> <target state="translated">Atributy sestavení a modulu musí předcházet přede všemi ostatními prvky definovanými v souboru s výjimkou klauzulí using a deklarací externích aliasů.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionExpected"> <source>Expected expression</source> <target state="translated">Očekával se výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSubsystemVersion"> <source>Invalid version {0} for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise</source> <target state="translated">Neplatná verze {0} pro /subsystemversion. Verze musí být 6.02 nebo vyšší pro ARM nebo AppContainerExe a 4.00 nebo vyšší v ostatních případech.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropMethodWithBody"> <source>Embedded interop method '{0}' contains a body.</source> <target state="translated">Vložená metoda spolupráce {0} obsahuje tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_BadWarningLevel"> <source>Warning level must be zero or greater</source> <target state="translated">Úroveň upozornění musí být nula nebo větší.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDebugType"> <source>Invalid option '{0}' for /debug; must be 'portable', 'embedded', 'full' or 'pdbonly'</source> <target state="translated">Neplatný parametr {0} pro /debug; musí být portable, embedded, full nebo pdbonly.</target> <note /> </trans-unit> <trans-unit id="ERR_BadResourceVis"> <source>Invalid option '{0}'; Resource visibility must be either 'public' or 'private'</source> <target state="translated">Neplatná možnost {0}. Viditelnost zdroje musí být public nebo private.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueTypeMustMatch"> <source>The type of the argument to the DefaultParameterValue attribute must match the parameter type</source> <target state="translated">Typ argumentu atributu DefaultParameterValue musí odpovídat typu parametru.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueBadValueType"> <source>Argument of type '{0}' is not applicable for the DefaultParameterValue attribute</source> <target state="translated">Argument typu {0} není použitelný pro atribut DefaultParameterValue.</target> <note /> </trans-unit> <trans-unit id="ERR_MemberAlreadyInitialized"> <source>Duplicate initialization of member '{0}'</source> <target state="translated">Duplicitní inicializace členu {0}</target> <note /> </trans-unit> <trans-unit id="ERR_MemberCannotBeInitialized"> <source>Member '{0}' cannot be initialized. It is not a field or property.</source> <target state="translated">Člen {0} nejde inicializovat. Nejedná se o pole ani vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_StaticMemberInObjectInitializer"> <source>Static field or property '{0}' cannot be assigned in an object initializer</source> <target state="translated">Statické pole nebo vlastnost {0} se nedá přiřadit k inicializátoru objektu.</target> <note /> </trans-unit> <trans-unit id="ERR_ReadonlyValueTypeInObjectInitializer"> <source>Members of readonly field '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type</source> <target state="translated">Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu.</target> <note /> </trans-unit> <trans-unit id="ERR_ValueTypePropertyInObjectInitializer"> <source>Members of property '{0}' of type '{1}' cannot be assigned with an object initializer because it is of a value type</source> <target state="translated">Členy vlastnosti {0} typu {1} nejde přiřadit k inicializátoru objektu, protože tento inicializátor je hodnotového typu.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeTypeInObjectCreation"> <source>Unsafe type '{0}' cannot be used in object creation</source> <target state="translated">K vytvoření objektu nejde použít nezabezpečený typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyElementInitializer"> <source>Element initializer cannot be empty</source> <target state="translated">Inicializátor prvku nemůže být prázdný.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerAddHasWrongSignature"> <source>The best overloaded method match for '{0}' has wrong signature for the initializer element. The initializable Add must be an accessible instance method.</source> <target state="translated">Odpovídající optimální přetěžovaná metoda pro {0} má nesprávný podpis prvku inicializátoru. Jako inicializovatelná metoda Add se musí používat dostupná instanční metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_CollectionInitRequiresIEnumerable"> <source>Cannot initialize type '{0}' with a collection initializer because it does not implement 'System.Collections.IEnumerable'</source> <target state="translated">Nejde inicializovat typ {0} pomocí inicializátoru kolekce, protože neimplementuje System.Collections.IEnumerable.</target> <note /> </trans-unit> <trans-unit id="ERR_CantSetWin32Manifest"> <source>Error reading Win32 manifest file '{0}' -- '{1}'</source> <target state="translated">Chyba při čtení souboru manifestu Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="WRN_CantHaveManifestForModule"> <source>Ignoring /win32manifest for module because it only applies to assemblies</source> <target state="translated">Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením.</target> <note /> </trans-unit> <trans-unit id="WRN_CantHaveManifestForModule_Title"> <source>Ignoring /win32manifest for module because it only applies to assemblies</source> <target state="translated">Přepínač /win32manifest pro modul se bude ignorovat, protože se vztahuje jenom k sestavením.</target> <note /> </trans-unit> <trans-unit id="ERR_BadInstanceArgType"> <source>'{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' requires a receiver of type '{3}'</source> <target state="translated">{0} neobsahuje definici pro {1} a přetížení optimální metody rozšíření {2} vyžaduje přijímač typu {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryDuplicateRangeVariable"> <source>The range variable '{0}' has already been declared</source> <target state="translated">Proměnná rozsahu {0} je už deklarovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableOverrides"> <source>The range variable '{0}' conflicts with a previous declaration of '{0}'</source> <target state="translated">Proměnná rozsahu {0} je v konfliktu s předchozí deklarací {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableAssignedBadValue"> <source>Cannot assign {0} to a range variable</source> <target state="translated">{0} nejde přiřadit k proměnné rozsahu.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProviderCastable"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Consider explicitly specifying the type of the range variable '{2}'.</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Zvažte možnost explicitního určení typu proměnné rozsahu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProviderStandard"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. Are you missing required assembly references or a using directive for 'System.Linq'?</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}. Nechybí odkazy na požadovaná sestavení nebo direktiva using pro System.Linq?</target> <note /> </trans-unit> <trans-unit id="ERR_QueryNoProvider"> <source>Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found.</source> <target state="translated">Nenašla se implementace vzorku dotazu pro typ zdroje {0}. Nenašel se prvek {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOuterKey"> <source>The name '{0}' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.</source> <target state="translated">Název {0} není v oboru levé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryInnerKey"> <source>The name '{0}' is not in scope on the right side of 'equals'. Consider swapping the expressions on either side of 'equals'.</source> <target state="translated">Název {0} není v oboru pravé strany operátoru equals. Zvažte možnost vzájemné záměny výrazů na obou stranách operátoru equals.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryOutRefRangeVariable"> <source>Cannot pass the range variable '{0}' as an out or ref parameter</source> <target state="translated">Proměnnou rozsahu {0} nejde předat jako vnější nebo odkazovaný parametr.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryMultipleProviders"> <source>Multiple implementations of the query pattern were found for source type '{0}'. Ambiguous call to '{1}'.</source> <target state="translated">Našlo se víc implementací vzorku dotazu pro typ zdroje {0}. Nejednoznačné volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailedMulti"> <source>The type of one of the expressions in the {0} clause is incorrect. Type inference failed in the call to '{1}'.</source> <target state="translated">Typ jednoho z výrazů v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailed"> <source>The type of the expression in the {0} clause is incorrect. Type inference failed in the call to '{1}'.</source> <target state="translated">Typ výrazu v klauzuli {0} je nesprávný. Nepovedlo se odvození typu při volání funkce {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryTypeInferenceFailedSelectMany"> <source>An expression of type '{0}' is not allowed in a subsequent from clause in a query expression with source type '{1}'. Type inference failed in the call to '{2}'.</source> <target state="translated">Není povolené použití výrazu typu {0} v následné klauzuli from ve výrazu dotazu s typem zdroje {1}. Nepovedlo se odvození typu při volání funkce {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsPointerOp"> <source>An expression tree may not contain an unsafe pointer operation</source> <target state="translated">Strom výrazů nesmí obsahovat nezabezpečenou operaci s ukazatelem.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsAnonymousMethod"> <source>An expression tree may not contain an anonymous method expression</source> <target state="translated">Strom výrazů nesmí obsahovat výraz anonymní metody.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonymousMethodToExpressionTree"> <source>An anonymous method expression cannot be converted to an expression tree</source> <target state="translated">Výraz anonymní metody nejde převést na strom výrazu.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableReadOnly"> <source>Range variable '{0}' cannot be assigned to -- it is read only</source> <target state="translated">K proměnné rozsahu {0} nejde přiřazovat – je jenom pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_QueryRangeVariableSameAsTypeParam"> <source>The range variable '{0}' cannot have the same name as a method type parameter</source> <target state="translated">Proměnná rozsahu {0} nesmí mít stejný název jako parametr typu metody.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeVarNotFoundRangeVariable"> <source>The contextual keyword 'var' cannot be used in a range variable declaration</source> <target state="translated">V deklaraci proměnné rozsahu nejde použít kontextové klíčové slovo var.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgTypesForCollectionAdd"> <source>The best overloaded Add method '{0}' for the collection initializer has some invalid arguments</source> <target state="translated">Některé argumenty optimální přetěžované metody Add {0} pro inicializátor kolekce jsou neplatné.</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefParameterInExpressionTree"> <source>An expression tree lambda may not contain a ref, in or out parameter</source> <target state="translated">Strom výrazu lambda nesmí obsahovat parametr ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_VarArgsInExpressionTree"> <source>An expression tree lambda may not contain a method with variable arguments</source> <target state="translated">Strom výrazu lambda nesmí obsahovat metodu s proměnnými argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_MemGroupInExpressionTree"> <source>An expression tree lambda may not contain a method group</source> <target state="translated">Strom výrazu lambda nesmí obsahovat skupinu metod.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerAddHasParamModifiers"> <source>The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.</source> <target state="translated">Optimální nalezenou přetěžovanou metodu {0} pro element inicializátoru kolekce nejde použít. Metody Add inicializátoru kolekce nemůžou mít parametry Ref nebo Out.</target> <note /> </trans-unit> <trans-unit id="ERR_NonInvocableMemberCalled"> <source>Non-invocable member '{0}' cannot be used like a method.</source> <target state="translated">Nevyvolatelného člena {0} nejde použít jako metodu.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches"> <source>Member '{0}' implements interface member '{1}' in type '{2}'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called.</source> <target state="translated">Člen {0} implementuje člen rozhraní {1} v typu {2}. Za běhu existuje pro tohoto člena rozhraní víc shod. Volaná metoda závisí na konkrétní implementaci.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches_Title"> <source>Member implements interface member with multiple matches at run-time</source> <target state="translated">Člen za běhu implementuje člena rozhraní s více shodami.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeImplementationMatches_Description"> <source>This warning can be generated when two interface methods are differentiated only by whether a particular parameter is marked with ref or with out. It is best to change your code to avoid this warning because it is not obvious or guaranteed which method is called at runtime. Although C# distinguishes between out and ref, the CLR sees them as the same. When deciding which method implements the interface, the CLR just picks one. Give the compiler some way to differentiate the methods. For example, you can give them different names or provide an additional parameter on one of them.</source> <target state="translated">Toto varování se může vygenerovat, když jsou dvě metody rozhraní odlišené jenom tím, že určitý parametr je označený jednou jako ref a podruhé jako out. Doporučuje se kód změnit tak, aby k tomuto varování nedocházelo, protože není úplně jasné nebo zaručené, která metoda se má za běhu vyvolat. Ačkoli C# rozlišuje mezi out a ref, pro CLR je to totéž. Při rozhodování, která metoda má implementovat rozhraní, modul CLR prostě jednu vybere. Poskytněte kompilátoru nějaký způsob, jak metody rozlišit. Můžete například zadat různé názvy nebo k jedné z nich přidat parametr navíc.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeOverrideMatches"> <source>Member '{1}' overrides '{0}'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime.</source> <target state="translated">Člen {1} přepisuje člen {0}. Za běhu existuje více kandidátů na přepis. Volaná metoda závisí na konkrétní implementaci. Použijte prosím novější modul runtime.</target> <note /> </trans-unit> <trans-unit id="WRN_MultipleRuntimeOverrideMatches_Title"> <source>Member overrides base member with multiple override candidates at run-time</source> <target state="translated">Člen za běhu přepíše základního člena s více kandidáty na přepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_ObjectOrCollectionInitializerWithDelegateCreation"> <source>Object and collection initializer expressions may not be applied to a delegate creation expression</source> <target state="translated">Výrazy inicializátoru objektu a kolekce nejde použít na výraz vytvářející delegáta.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidConstantDeclarationType"> <source>'{0}' is of type '{1}'. The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type.</source> <target state="translated">{0} je typu {1}. V deklaraci konstanty musí být uvedený typ sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, výčtový typ nebo typ odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_FileNotFound"> <source>Source file '{0}' could not be found.</source> <target state="translated">Zdrojový soubor {0} se nenašel.</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded"> <source>Source file '{0}' specified multiple times</source> <target state="translated">Zdrojový soubor {0} je zadaný několikrát.</target> <note /> </trans-unit> <trans-unit id="WRN_FileAlreadyIncluded_Title"> <source>Source file specified multiple times</source> <target state="translated">Zdrojový soubor je zadaný několikrát.</target> <note /> </trans-unit> <trans-unit id="ERR_NoFileSpec"> <source>Missing file specification for '{0}' option</source> <target state="translated">Pro možnost {0} chybí specifikace souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsString"> <source>Command-line syntax error: Missing '{0}' for '{1}' option</source> <target state="translated">Chyba syntaxe příkazového řádku: Nenašla se hodnota {0} pro možnost {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSwitch"> <source>Unrecognized option: '{0}'</source> <target state="translated">Nerozpoznaná možnost: {0}</target> <note /> </trans-unit> <trans-unit id="WRN_NoSources"> <source>No source files specified.</source> <target state="translated">Nejsou zadané žádné zdrojové soubory.</target> <note /> </trans-unit> <trans-unit id="WRN_NoSources_Title"> <source>No source files specified</source> <target state="translated">Nejsou zadané žádné zdrojové soubory.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpectedSingleScript"> <source>Expected a script (.csx file) but none specified</source> <target state="translated">Očekával se skript (soubor .csx), žádný ale není zadaný.</target> <note /> </trans-unit> <trans-unit id="ERR_OpenResponseFile"> <source>Error opening response file '{0}'</source> <target state="translated">Chyba při otevírání souboru odpovědí {0}</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenFileWrite"> <source>Cannot open '{0}' for writing -- '{1}'</source> <target state="translated">{0} se nedá otevřít pro zápis -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadBaseNumber"> <source>Invalid image base number '{0}'</source> <target state="translated">Neplatné základní číslo obrázku {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BinaryFile"> <source>'{0}' is a binary file instead of a text file</source> <target state="translated">{0} je binární, ne textový soubor.</target> <note /> </trans-unit> <trans-unit id="FTL_BadCodepage"> <source>Code page '{0}' is invalid or not installed</source> <target state="translated">Znaková stránka {0} je neplatná nebo není nainstalovaná.</target> <note /> </trans-unit> <trans-unit id="FTL_BadChecksumAlgorithm"> <source>Algorithm '{0}' is not supported</source> <target state="translated">Algoritmus {0} není podporovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_NoMainOnDLL"> <source>Cannot specify /main if building a module or library</source> <target state="translated">Při vytváření modulu nebo knihovny nejde použít přepínač /main.</target> <note /> </trans-unit> <trans-unit id="FTL_InvalidTarget"> <source>Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'</source> <target state="translated">Neplatný typ cíle pro parametr /target: Je nutné použít možnost exe, winexe, library nebo module.</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigNotOnCommandLine"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí.</target> <note /> </trans-unit> <trans-unit id="WRN_NoConfigNotOnCommandLine_Title"> <source>Ignoring /noconfig option because it was specified in a response file</source> <target state="translated">Přepínač /noconfig se ignoroval, protože byl uvedený v souboru odpovědí.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFileAlignment"> <source>Invalid file section alignment '{0}'</source> <target state="translated">Neplatný argument výběru souboru {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidOutputName"> <source>Invalid output name: {0}</source> <target state="translated">Neplatný název výstupu: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInformationFormat"> <source>Invalid debug information format: {0}</source> <target state="translated">Neplatný formát informací o ladění: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_LegacyObjectIdSyntax"> <source>'id#' syntax is no longer supported. Use '$id' instead.</source> <target state="translated">'Syntaxe id# už není podporovaná. Použijte místo ní syntaxi $id.</target> <note /> </trans-unit> <trans-unit id="WRN_DefineIdentifierRequired"> <source>Invalid name for a preprocessing symbol; '{0}' is not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; {0} není platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="WRN_DefineIdentifierRequired_Title"> <source>Invalid name for a preprocessing symbol; not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; neplatný identifikátor</target> <note /> </trans-unit> <trans-unit id="FTL_OutputFileExists"> <source>Cannot create short filename '{0}' when a long filename with the same short filename already exists</source> <target state="translated">Nejde vytvořit krátký název souboru {0}, protože už existuje dlouhý název souboru se stejným krátkým názvem.</target> <note /> </trans-unit> <trans-unit id="ERR_OneAliasPerReference"> <source>A /reference option that declares an extern alias can only have one filename. To specify multiple aliases or filenames, use multiple /reference options.</source> <target state="translated">Parametr /reference deklarující externí alias může mít jenom jeden název souboru. Pokud chcete zadat víc aliasů nebo názvů souborů, použijte více parametrů /reference.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchNeedsNumber"> <source>Command-line syntax error: Missing ':&lt;number&gt;' for '{0}' option</source> <target state="translated">Chyba syntaxe příkazového řádku: Nenašla se hodnota :&lt;číslo&gt; parametru {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingDebugSwitch"> <source>The /pdb option requires that the /debug option also be used</source> <target state="translated">Možnost /pdb vyžaduje taky použití možnosti /debug .</target> <note /> </trans-unit> <trans-unit id="ERR_ComRefCallInExpressionTree"> <source>An expression tree lambda may not contain a COM call with ref omitted on arguments</source> <target state="translated">Strom výrazu lambda nesmí obsahovat volání COM, které v argumentech vynechává parametr Ref.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidFormatForGuidForOption"> <source>Command-line syntax error: Invalid Guid format '{0}' for option '{1}'</source> <target state="translated">Chyba syntaxe příkazového řádku: Neplatný formát GUID {0} pro možnost {1}</target> <note /> </trans-unit> <trans-unit id="ERR_MissingGuidForOption"> <source>Command-line syntax error: Missing Guid for option '{1}'</source> <target state="translated">Chyba syntaxe příkazového řádku: Chybí GUID pro možnost {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoVarArgs"> <source>Methods with variable arguments are not CLS-compliant</source> <target state="translated">Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoVarArgs_Title"> <source>Methods with variable arguments are not CLS-compliant</source> <target state="translated">Metody s proměnnými argumenty nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadArgType"> <source>Argument type '{0}' is not CLS-compliant</source> <target state="translated">Typ argumentu {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadArgType_Title"> <source>Argument type is not CLS-compliant</source> <target state="translated">Typ argumentu není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadReturnType"> <source>Return type of '{0}' is not CLS-compliant</source> <target state="translated">Typ vrácené hodnoty {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadReturnType_Title"> <source>Return type is not CLS-compliant</source> <target state="translated">Návratový typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType"> <source>Type of '{0}' is not CLS-compliant</source> <target state="translated">Typ {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType_Title"> <source>Type is not CLS-compliant</source> <target state="translated">Typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadFieldPropType_Description"> <source>A public, protected, or protected internal variable must be of a type that is compliant with the Common Language Specification (CLS).</source> <target state="translated">Veřejná, chráněná nebo interně chráněná proměnná musí být typu, který je kompatibilní se specifikací CLS (Common Language Specification).</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifierCase"> <source>Identifier '{0}' differing only in case is not CLS-compliant</source> <target state="translated">Identifikátor {0} lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifierCase_Title"> <source>Identifier differing only in case is not CLS-compliant</source> <target state="translated">Identifikátor lišící se jenom použitím velkých a malých písmen není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadRefOut"> <source>Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda {0} lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadRefOut_Title"> <source>Overloaded method differing only in ref or out, or in array rank, is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda lišící se jen parametrem ref nebo out nebo rozměrem pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed"> <source>Overloaded method '{0}' differing only by unnamed array types is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda {0} lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed_Title"> <source>Overloaded method differing only by unnamed array types is not CLS-compliant</source> <target state="translated">Přetěžovaná metoda lišící se jenom nepojmenovanými typy pole není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_OverloadUnnamed_Description"> <source>This error occurs if you have an overloaded method that takes a jagged array and the only difference between the method signatures is the element type of the array. To avoid this error, consider using a rectangular array rather than a jagged array; use an additional parameter to disambiguate the function call; rename one or more of the overloaded methods; or, if CLS Compliance is not needed, remove the CLSCompliantAttribute attribute.</source> <target state="translated">Tato chyba se objeví, pokud máte přetěžovanou metodu, která přebírá vícenásobné pole, a jediný rozdíl mezi signaturami metody je typ elementu tohoto pole. Aby nedošlo k této chybě, zvažte použití pravoúhlého pole namísto vícenásobného, použijte další parametr, aby volání této funkce bylo jednoznačné, přejmenujte nejmíň jednu přetěžovanou metodu nebo (pokud kompatibilita s CLS není nutná) odeberte atribut CLSCompliantAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifier"> <source>Identifier '{0}' is not CLS-compliant</source> <target state="translated">Identifikátor {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadIdentifier_Title"> <source>Identifier is not CLS-compliant</source> <target state="translated">Identifikátor není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase"> <source>'{0}': base type '{1}' is not CLS-compliant</source> <target state="translated">{0}: Základní typ {1} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase_Title"> <source>Base type is not CLS-compliant</source> <target state="translated">Základní typ není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadBase_Description"> <source>A base type was marked as not having to be compliant with the Common Language Specification (CLS) in an assembly that was marked as being CLS compliant. Either remove the attribute that specifies the assembly is CLS compliant or remove the attribute that indicates the type is not CLS compliant.</source> <target state="translated">Základní typ byl označený tak, že nemusí být kompatibilní se specifikací CLS (Common Language Specification) v sestavení, které bylo označené jako kompatibilní s CLS. Buď odeberte atribut, který sestavení určuje jako kompatibilní s CLS, nebo odeberte atribut, který označuje typ jako nekompatibilní s CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterfaceMember"> <source>'{0}': CLS-compliant interfaces must have only CLS-compliant members</source> <target state="translated">{0}: Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterfaceMember_Title"> <source>CLS-compliant interfaces must have only CLS-compliant members</source> <target state="translated">Rozhraní kompatibilní se specifikací CLS musí obsahovat jenom členy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoAbstractMembers"> <source>'{0}': only CLS-compliant members can be abstract</source> <target state="translated">{0}: Jenom členy kompatibilní se specifikací CLS můžou být abstraktní.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NoAbstractMembers_Title"> <source>Only CLS-compliant members can be abstract</source> <target state="translated">Jenom členy kompatibilní se specifikací CLS můžou být abstraktní.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules"> <source>You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking</source> <target state="translated">Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules_Title"> <source>You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking</source> <target state="translated">Pokud chcete povolit kontrolu kompatibility se specifikací CLS, musíte zadat atribut CLSCompliant sestavení, ne modulu.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ModuleMissingCLS"> <source>Added modules must be marked with the CLSCompliant attribute to match the assembly</source> <target state="translated">Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ModuleMissingCLS_Title"> <source>Added modules must be marked with the CLSCompliant attribute to match the assembly</source> <target state="translated">Aby přidávané moduly odpovídaly sestavení, musí být označené atributem CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS"> <source>'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute</source> <target state="translated">{0} nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS_Title"> <source>Type or member cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute</source> <target state="translated">Typ nebo člen nejde označit jako kompatibilní se specifikací CLS, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadAttributeType"> <source>'{0}' has no accessible constructors which use only CLS-compliant types</source> <target state="translated">{0} nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadAttributeType_Title"> <source>Type has no accessible constructors which use only CLS-compliant types</source> <target state="translated">Typ nemá žádné přístupné konstruktory, které používají jenom typy kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ArrayArgumentToAttribute"> <source>Arrays as attribute arguments is not CLS-compliant</source> <target state="translated">Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_ArrayArgumentToAttribute_Title"> <source>Arrays as attribute arguments is not CLS-compliant</source> <target state="translated">Pole jako argumenty atributu nejsou kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules2"> <source>You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly</source> <target state="translated">Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_NotOnModules2_Title"> <source>You cannot specify the CLSCompliant attribute on a module that differs from the CLSCompliant attribute on the assembly</source> <target state="translated">Nejde zadat atribut CLSCompliant u modulu, který se liší od atributu CLSCompliant sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_IllegalTrueInFalse"> <source>'{0}' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type '{1}'</source> <target state="translated">{0} nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu {1}, který není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_IllegalTrueInFalse_Title"> <source>Type cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type</source> <target state="translated">Typ nejde označit jako kompatibilní se specifikací CLS, protože se jedná o člen typu, který není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnPrivateType"> <source>CLS compliance checking will not be performed on '{0}' because it is not visible from outside this assembly</source> <target state="translated">Pro prvek {0} se neprovede kontrola kompatibility se specifikací CLS, protože není viditelný mimo toto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnPrivateType_Title"> <source>CLS compliance checking will not be performed because it is not visible from outside this assembly</source> <target state="translated">Kontrola kompatibility se specifikací CLS se neprovede, protože není viditelná zvnějšku tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS2"> <source>'{0}' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute</source> <target state="translated">{0} nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_AssemblyNotCLS2_Title"> <source>Type or member does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute</source> <target state="translated">Typ nebo člen nepotřebuje atribut CLSCompliant, protože sestavení nemá atribut CLSCompliant.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnParam"> <source>CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead.</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u parametrů. Použijte jej místo toho u metody.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnParam_Title"> <source>CLSCompliant attribute has no meaning when applied to parameters</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u parametrů.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnReturn"> <source>CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead.</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u typů vrácených hodnot. Použijte jej místo toho u metody.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_MeaninglessOnReturn_Title"> <source>CLSCompliant attribute has no meaning when applied to return types</source> <target state="translated">Atribut CLSCompliant nemá žádný význam při použití u návratových typů.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadTypeVar"> <source>Constraint type '{0}' is not CLS-compliant</source> <target state="translated">Typ omezení {0} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadTypeVar_Title"> <source>Constraint type is not CLS-compliant</source> <target state="translated">Typ omezení není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_VolatileField"> <source>CLS-compliant field '{0}' cannot be volatile</source> <target state="translated">Pole kompatibilní se specifikací CLS {0} nemůže být typu volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_VolatileField_Title"> <source>CLS-compliant field cannot be volatile</source> <target state="translated">Pole kompatibilní se specifikací CLS nemůže být typu volatile.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterface"> <source>'{0}' is not CLS-compliant because base interface '{1}' is not CLS-compliant</source> <target state="translated">{0} není kompatibilní se specifikací CLS, protože základní rozhraní {1} není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="WRN_CLS_BadInterface_Title"> <source>Type is not CLS-compliant because base interface is not CLS-compliant</source> <target state="translated">Typ není kompatibilní se specifikací CLS, protože základní rozhraní není kompatibilní se specifikací CLS.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArg"> <source>'await' requires that the type {0} have a suitable 'GetAwaiter' method</source> <target state="translated">'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArgIntrinsic"> <source>Cannot await '{0}'</source> <target state="translated">Operátor await nejde použít pro {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaiterPattern"> <source>'await' requires that the return type '{0}' of '{1}.GetAwaiter()' have suitable 'IsCompleted', 'OnCompleted', and 'GetResult' members, and implement 'INotifyCompletion' or 'ICriticalNotifyCompletion'</source> <target state="translated">'Operátor await vyžaduje, aby návratový typ {0} metody {1}.GetAwaiter() měl odpovídající členy IsCompleted, OnCompleted a GetResult a implementoval rozhraní INotifyCompletion nebo ICriticalNotifyCompletion.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArg_NeedSystem"> <source>'await' requires that the type '{0}' have a suitable 'GetAwaiter' method. Are you missing a using directive for 'System'?</source> <target state="translated">'Operátor await vyžaduje, aby typ {0} měl odpovídající metodu GetAwaiter. Chybí vám direktiva using pro položku System?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitArgVoidCall"> <source>Cannot await 'void'</source> <target state="translated">Operátor await nejde použít pro void.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitAsIdentifier"> <source>'await' cannot be used as an identifier within an async method or lambda expression</source> <target state="translated">'Operátor Await nejde použít jako identifikátor v asynchronní metodě nebo výrazu lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_DoesntImplementAwaitInterface"> <source>'{0}' does not implement '{1}'</source> <target state="translated">{0} neimplementuje {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TaskRetNoObjectRequired"> <source>Since '{0}' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task&lt;T&gt;'?</source> <target state="translated">Protože metoda {0} je asynchronní a její návratový typ je Task, za klíčovým slovem return nesmí následovat objektový výraz. Měli jste v úmyslu vrátit hodnotu typu Task&lt;T&gt;?</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncReturn"> <source>The return type of an async method must be void, Task, Task&lt;T&gt;, a task-like type, IAsyncEnumerable&lt;T&gt;, or IAsyncEnumerator&lt;T&gt;</source> <target state="translated">Návratový typ asynchronní metody musí být void, Task, Task&lt;T&gt;, typ podobný úloze, IAsyncEnumerable&lt;T&gt; nebo IAsyncEnumerator&lt;T&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReturnVoid"> <source>Cannot return an expression of type 'void'</source> <target state="translated">Nejde vrátit výraz typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_VarargsAsync"> <source>__arglist is not allowed in the parameter list of async methods</source> <target state="translated">Klíčové slovo __arglist není povolené v seznamu parametrů asynchronních metod.</target> <note /> </trans-unit> <trans-unit id="ERR_ByRefTypeAndAwait"> <source>'await' cannot be used in an expression containing the type '{0}'</source> <target state="translated">'Operátor await nejde použít ve výrazu, který obsahuje typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsafeAsyncArgType"> <source>Async methods cannot have unsafe parameters or return types</source> <target state="translated">Asynchronní metody nemůžou mít návratové typy nebo parametry, které nejsou bezpečné.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncArgType"> <source>Async methods cannot have ref, in or out parameters</source> <target state="translated">Asynchronní metody nemůžou mít parametry ref, in nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsync"> <source>The 'await' operator can only be used when contained within a method or lambda expression marked with the 'async' modifier</source> <target state="translated">Operátor await jde použít, jenom pokud je obsažen v metodě nebo výrazu lambda označeném pomocí modifikátoru async.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsyncLambda"> <source>The 'await' operator can only be used within an async {0}. Consider marking this {0} with the 'async' modifier.</source> <target state="translated">Operátor await jde použít jenom v asynchronní metodě {0}. Zvažte označení této metody modifikátorem async.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutAsyncMethod"> <source>The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task&lt;{0}&gt;'.</source> <target state="translated">Operátor await jde použít jenom v asynchronních metodách. Zvažte označení této metody modifikátorem async a změnu jejího návratového typu na Task&lt;{0}&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitWithoutVoidAsyncMethod"> <source>The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.</source> <target state="translated">Operátor await jde použít jenom v asynchronní metodě. Zvažte označení této metody pomocí modifikátoru async a změnu jejího návratového typu na Task.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInFinally"> <source>Cannot await in the body of a finally clause</source> <target state="translated">Nejde použít operátor await v těle klauzule finally.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInCatch"> <source>Cannot await in a catch clause</source> <target state="translated">Operátor await nejde použít v klauzuli catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInCatchFilter"> <source>Cannot await in the filter expression of a catch clause</source> <target state="translated">Nejde použít operátor await ve výrazu filtru klauzule catch.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInLock"> <source>Cannot await in the body of a lock statement</source> <target state="translated">Operátor await nejde použít v příkazu lock.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInStaticVariableInitializer"> <source>The 'await' operator cannot be used in a static script variable initializer.</source> <target state="translated">Operátor await nejde použít v inicializátoru proměnné statického skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_AwaitInUnsafeContext"> <source>Cannot await in an unsafe context</source> <target state="translated">Operátor await nejde použít v nezabezpečeném kontextu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncLacksBody"> <source>The 'async' modifier can only be used in methods that have a body.</source> <target state="translated">Modifikátor async se dá použít jenom v metodách, které mají tělo.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecialByRefLocal"> <source>Parameters or locals of type '{0}' cannot be declared in async methods or async lambda expressions.</source> <target state="translated">Parametry nebo lokální proměnné typu {0} nemůžou být deklarované v asynchronních metodách nebo asynchronních výrazech lambda.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSpecialByRefIterator"> <source>foreach statement cannot operate on enumerators of type '{0}' in async or iterator methods because '{0}' is a ref struct.</source> <target state="translated">Výraz foreach nejde použít na enumerátorech typu {0} v asynchronních metodách nebo metodách iterátoru, protože {0} je struktura REF.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync"> <source>Security attribute '{0}' cannot be applied to an Async method.</source> <target state="translated">Atribut zabezpečení {0} nejde použít pro metodu Async.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct"> <source>Async methods are not allowed in an Interface, Class, or Structure which has the 'SecurityCritical' or 'SecuritySafeCritical' attribute.</source> <target state="translated">Asynchronní metody nejsou povolené v rozhraní, třídě nebo struktuře, které mají atribut SecurityCritical nebo SecuritySafeCritical.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAwaitInQuery"> <source>The 'await' operator may only be used in a query expression within the first collection expression of the initial 'from' clause or within the collection expression of a 'join' clause</source> <target state="translated">Operátor await jde použít jenom ve výrazu dotazu v rámci první kolekce výrazu počáteční klauzule from nebo v rámci výrazu kolekce klauzule join.</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits"> <source>This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.</source> <target state="translated">V této asynchronní metodě chybí operátory await a spustí se synchronně. Zvažte použití operátoru await pro čekání na neblokující volání rozhraní API nebo vykonání činnosti vázané na procesor ve vlákně na pozadí pomocí výrazu await Task.Run(...).</target> <note /> </trans-unit> <trans-unit id="WRN_AsyncLacksAwaits_Title"> <source>Async method lacks 'await' operators and will run synchronously</source> <target state="translated">V této asynchronní metodě chybí operátory await a spustí se synchronně.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression"> <source>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.</source> <target state="translated">Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání. Zvažte použití operátoru await na výsledek volání.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Title"> <source>Because this call is not awaited, execution of the current method continues before the call is completed</source> <target state="translated">Protože se toto volání neočekává, vykonávání aktuální metody pokračuje před dokončením volání.</target> <note /> </trans-unit> <trans-unit id="WRN_UnobservedAwaitableExpression_Description"> <source>The current method calls an async method that returns a Task or a Task&lt;TResult&gt; and doesn't apply the await operator to the result. The call to the async method starts an asynchronous task. However, because no await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't what you expect. Usually other aspects of the calling method depend on the results of the call or, minimally, the called method is expected to complete before you return from the method that contains the call. An equally important issue is what happens to exceptions that are raised in the called async method. An exception that's raised in a method that returns a Task or Task&lt;TResult&gt; is stored in the returned task. If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. You should consider suppressing the warning only if you're sure that you don't want to wait for the asynchronous call to complete and that the called method won't raise any exceptions. In that case, you can suppress the warning by assigning the task result of the call to a variable.</source> <target state="translated">Aktuální metoda volá asynchronní metodu, která vrací úlohu nebo úlohu&lt;TResult&gt; a ve výsledku nepoužije operátor await. Volání asynchronní metody spustí asynchronní úlohu. Vzhledem k tomu, že se ale nepoužil žádný operátor await, bude program pokračovat bez čekání na dokončení úlohy. Ve většině případů se nejedná o chování, které byste očekávali. Ostatní aspekty volání metody obvykle závisí na výsledcích volání nebo se aspoň očekává, že se volaná metoda dokončí před vaším návratem z metody obsahující volání. Stejně důležité je i to, co se stane s výjimkami, ke kterým dojde ve volané asynchronní metodě. Výjimka, ke které dojde v metodě vracející úlohu nebo úlohu&lt;TResult&gt;, se uloží do vrácené úlohy. Pokud úlohu neočekáváte nebo explicitně výjimky nekontrolujete, dojde ke ztrátě výjimky. Pokud úlohu očekáváte, dojde k výjimce znovu. Nejvhodnějším postupem je volání vždycky očekávat. Potlačení upozornění zvažte jenom v případě, když určitě nechcete čekat na dokončení asynchronního volání a jste si jistí, že volaná metoda nevyvolá žádné výjimky. V takovém případě můžete upozornění potlačit tak, že výsledek úlohy volání přidružíte proměnné.</target> <note /> </trans-unit> <trans-unit id="ERR_SynchronizedAsyncMethod"> <source>'MethodImplOptions.Synchronized' cannot be applied to an async method</source> <target state="translated">'Možnost MethodImplOptions.Synchronized nejde použít pro asynchronní metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerLineNumberParam"> <source>CallerLineNumberAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerLineNumberAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerFilePathParam"> <source>CallerFilePathAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerFilePathAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForCallerMemberNameParam"> <source>CallerMemberNameAttribute cannot be applied because there are no standard conversions from type '{0}' to type '{1}'</source> <target state="translated">CallerMemberNameAttribute nejde použít, protože neexistuje žádný standardní převod z typu {0} na {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerLineNumberParamWithoutDefaultValue"> <source>The CallerLineNumberAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerLineNumberAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerFilePathParamWithoutDefaultValue"> <source>The CallerFilePathAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerFilePathAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="ERR_BadCallerMemberNameParamWithoutDefaultValue"> <source>The CallerMemberNameAttribute may only be applied to parameters with default values</source> <target state="translated">Atribut CallerMemberNameAttribute jde použít jenom pro parametry s výchozími hodnotami.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberParamForUnconsumedLocation"> <source>The CallerLineNumberAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerLineNumberAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberParamForUnconsumedLocation_Title"> <source>The CallerLineNumberAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerLineNumberAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathParamForUnconsumedLocation"> <source>The CallerFilePathAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerFilePathAttribute použitý u parametru {0} nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathParamForUnconsumedLocation_Title"> <source>The CallerFilePathAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerFilePathAttribute nebude mít žádný vliv, protože se vztahuje na člen, který je použitý v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNameParamForUnconsumedLocation"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek, protože se aplikuje u člena, který se používá v kontextech nepovolujících volitelné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerMemberNameParamForUnconsumedLocation_Title"> <source>The CallerMemberNameAttribute will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_NoEntryPoint"> <source>Program does not contain a static 'Main' method suitable for an entry point</source> <target state="translated">Program neobsahuje statickou metodu Main vhodnou pro vstupní bod.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerIncorrectLength"> <source>An array initializer of length '{0}' is expected</source> <target state="translated">Očekává se inicializátor pole s délkou {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_ArrayInitializerExpected"> <source>A nested array initializer is expected</source> <target state="translated">Očekává se inicializátor vnořeného pole.</target> <note /> </trans-unit> <trans-unit id="ERR_IllegalVarianceSyntax"> <source>Invalid variance modifier. Only interface and delegate type parameters can be specified as variant.</source> <target state="translated">Modifikátor odchylky je neplatný. Jako variant můžou být určeny jenom parametry typu delegát nebo rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedAliasedName"> <source>Unexpected use of an aliased name</source> <target state="translated">Neočekávané použití názvu v aliasu</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedGenericName"> <source>Unexpected use of a generic name</source> <target state="translated">Neočekávané použití obecného názvu</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedUnboundGenericName"> <source>Unexpected use of an unbound generic name</source> <target state="translated">Neočekávané použití odvázaného obecného názvu</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalStatement"> <source>Expressions and statements can only occur in a method body</source> <target state="translated">Výrazy a příkazy se můžou vyskytnout jenom v těle metody.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentForArray"> <source>An array access may not have a named argument specifier</source> <target state="translated">Přístup k poli nemůže mít specifikátor pojmenovaného argumentu.</target> <note /> </trans-unit> <trans-unit id="ERR_NotYetImplementedInRoslyn"> <source>This language feature ('{0}') is not yet implemented.</source> <target state="translated">Tato jazyková funkce ({0}) zatím není implementovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueNotAllowed"> <source>Default values are not valid in this context.</source> <target state="translated">Výchozí hodnoty nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenIcon"> <source>Error opening icon file {0} -- {1}</source> <target state="translated">Chyba při otevírání souboru ikony {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_CantOpenWin32Manifest"> <source>Error opening Win32 manifest file {0} -- {1}</source> <target state="translated">Chyba při otevírání souboru manifestu Win32 {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorBuildingWin32Resources"> <source>Error building Win32 resources -- {0}</source> <target state="translated">Chyba při sestavování prostředků Win32 -- {0}</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueBeforeRequiredValue"> <source>Optional parameters must appear after all required parameters</source> <target state="translated">Volitelné parametry musí následovat po všech povinných parametrech</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitImplCollisionOnRefOut"> <source>Cannot inherit interface '{0}' with the specified type parameters because it causes method '{1}' to contain overloads which differ only on ref and out</source> <target state="translated">Nejde dědit rozhraní {0} se zadanými parametry typu, protože to způsobuje, že metoda {1} obsahuje víc přetížení, která se liší jen deklaracemi ref a out.</target> <note /> </trans-unit> <trans-unit id="ERR_PartialWrongTypeParamsVariance"> <source>Partial declarations of '{0}' must have the same type parameter names and variance modifiers in the same order</source> <target state="translated">Částečné deklarace {0} musí obsahovat názvy parametrů stejného typu a modifikátory odchylek ve stejném pořadí.</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedVariance"> <source>Invalid variance: The type parameter '{1}' must be {3} valid on '{0}'. '{1}' is {2}.</source> <target state="translated">Neplatná odchylka: Parametr typu {1} musí být {3} platný v {0}. {1} je {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromDynamic"> <source>'{0}': cannot derive from the dynamic type</source> <target state="translated">{0}: Nejde odvozovat z dynamického typu.</target> <note /> </trans-unit> <trans-unit id="ERR_DeriveFromConstructedDynamic"> <source>'{0}': cannot implement a dynamic interface '{1}'</source> <target state="translated">{0}: Nemůže implementovat dynamické rozhraní {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicTypeAsBound"> <source>Constraint cannot be the dynamic type</source> <target state="translated">Omezení nemůže být dynamický typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstructedDynamicTypeAsBound"> <source>Constraint cannot be a dynamic type '{0}'</source> <target state="translated">Omezení nemůže být dynamický typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicRequiredTypesMissing"> <source>One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?</source> <target state="translated">Jeden nebo více typů požadovaných pro kompilaci dynamického výrazu nejde najít. Nechybí odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_MetadataNameTooLong"> <source>Name '{0}' exceeds the maximum length allowed in metadata.</source> <target state="translated">Název {0} překračuje maximální délku povolenou v metadatech.</target> <note /> </trans-unit> <trans-unit id="ERR_AttributesNotAllowed"> <source>Attributes are not valid in this context.</source> <target state="translated">Atributy nejsou v tomto kontextu platné.</target> <note /> </trans-unit> <trans-unit id="ERR_ExternAliasNotAllowed"> <source>'extern alias' is not valid in this context</source> <target state="translated">'Alias extern není v tomto kontextu platný.</target> <note /> </trans-unit> <trans-unit id="WRN_IsDynamicIsConfusing"> <source>Using '{0}' to test compatibility with '{1}' is essentially identical to testing compatibility with '{2}' and will succeed for all non-null values</source> <target state="translated">Použití operátoru {0} pro testování kompatibility s typem {1} je v podstatě totožné s testováním kompatibility s typem {2} a bude úspěšné pro všechny hodnoty, které nejsou null.</target> <note /> </trans-unit> <trans-unit id="WRN_IsDynamicIsConfusing_Title"> <source>Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object'</source> <target state="translated">Použití operátoru is pro testování kompatibility s typem dynamic je v podstatě totožné s testováním kompatibility s typem Object.</target> <note /> </trans-unit> <trans-unit id="ERR_YieldNotAllowedInScript"> <source>Cannot use 'yield' in top-level script code</source> <target state="translated">Příkaz yield se nedá použít v kódu skriptu nejvyšší úrovně.</target> <note /> </trans-unit> <trans-unit id="ERR_NamespaceNotAllowedInScript"> <source>Cannot declare namespace in script code</source> <target state="translated">Obor názvů se nedá deklarovat v kódu skriptu.</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalAttributesNotAllowed"> <source>Assembly and module attributes are not allowed in this context</source> <target state="translated">Atributy sestavení a modulů nejsou v tomto kontextu povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDelegateType"> <source>Delegate '{0}' has no invoke method or an invoke method with a return type or parameter types that are not supported.</source> <target state="translated">Delegát {0} nemá žádnou metodu invoke nebo má jeho metoda invoke nepodporovaný návratový typ nebo typy parametrů.</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored"> <source>The entry point of the program is global code; ignoring '{0}' entry point.</source> <target state="translated">Vstupním bodem programu je globální kód. Vstupní bod {0} se ignoruje.</target> <note /> </trans-unit> <trans-unit id="WRN_MainIgnored_Title"> <source>The entry point of the program is global code; ignoring entry point</source> <target state="translated">Vstupním bodem programu je globální kód. Vstupní bod se ignoruje</target> <note /> </trans-unit> <trans-unit id="ERR_BadVisEventType"> <source>Inconsistent accessibility: event type '{1}' is less accessible than event '{0}'</source> <target state="translated">Nekonzistentní dostupnost: Typ události {1} je míň dostupný než událost {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgument"> <source>Named argument specifications must appear after all fixed arguments have been specified. Please use language version {0} or greater to allow non-trailing named arguments.</source> <target state="translated">Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů. Pokud chcete povolit pojmenované argumenty, které nejsou na konci, použijte prosím jazyk verze {0} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation"> <source>Named argument specifications must appear after all fixed arguments have been specified in a dynamic invocation.</source> <target state="translated">Specifikace pojmenovaných argumentů musí následovat po specifikaci všech pevných argumentů v dynamickém vyvolání.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedArgument"> <source>The best overload for '{0}' does not have a parameter named '{1}'</source> <target state="translated">Nejlepší přetížení pro {0} neobsahuje parametr s názvem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNamedArgumentForDelegateInvoke"> <source>The delegate '{0}' does not have a parameter named '{1}'</source> <target state="translated">Delegát {0} neobsahuje parametr s názvem {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_DuplicateNamedArgument"> <source>Named argument '{0}' cannot be specified multiple times</source> <target state="translated">Pojmenovaný argument {0} nejde zadat víckrát.</target> <note /> </trans-unit> <trans-unit id="ERR_NamedArgumentUsedInPositional"> <source>Named argument '{0}' specifies a parameter for which a positional argument has already been given</source> <target state="translated">Pojmenovaný argument {0} určuje parametr, pro který už byl poskytnut poziční argument.</target> <note /> </trans-unit> <trans-unit id="ERR_BadNonTrailingNamedArgument"> <source>Named argument '{0}' is used out-of-position but is followed by an unnamed argument</source> <target state="translated">Pojmenovaný argument {0} se používá mimo pozici, je ale následovaný nepojmenovaným argumentem.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueUsedWithAttributes"> <source>Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute</source> <target state="translated">Nejde zadat výchozí hodnotu parametru v kombinaci s atributy DefaultParameterAttribute nebo OptionalAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueMustBeConstant"> <source>Default parameter value for '{0}' must be a compile-time constant</source> <target state="translated">Výchozí hodnota parametru pro {0} musí být konstanta definovaná při kompilaci.</target> <note /> </trans-unit> <trans-unit id="ERR_RefOutDefaultValue"> <source>A ref or out parameter cannot have a default value</source> <target state="translated">Parametr Ref nebo Uut nemůže mít výchozí hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForExtensionParameter"> <source>Cannot specify a default value for the 'this' parameter</source> <target state="translated">Nejde zadat výchozí hodnotu pro parametr this.</target> <note /> </trans-unit> <trans-unit id="ERR_DefaultValueForParamsParameter"> <source>Cannot specify a default value for a parameter array</source> <target state="translated">Nejde zadat výchozí hodnotu pro pole parametrů.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForDefaultParam"> <source>A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}'</source> <target state="translated">Hodnotu typu {0} nejde použít jako výchozí parametr, protože neexistují žádné standardní převody na typ {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoConversionForNubDefaultParam"> <source>A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type</source> <target state="translated">Hodnotu typu {0} nejde použít jako výchozí hodnotu parametru {1} s možnou hodnotou null, protože {0} není jednoduchý typ.</target> <note /> </trans-unit> <trans-unit id="ERR_NotNullRefDefaultParameter"> <source>'{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null</source> <target state="translated">{0} je typu {1}. Výchozí hodnotu parametru s jiným než řetězcovým typem odkazu jde inicializovat jenom hodnotou null.</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultValueForUnconsumedLocation"> <source>The default value specified for parameter '{0}' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">Výchozí hodnota zadaná pro parametr {0} nebude mít žádný efekt, protože platí pro člen, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="WRN_DefaultValueForUnconsumedLocation_Title"> <source>The default value specified will have no effect because it applies to a member that is used in contexts that do not allow optional arguments</source> <target state="translated">Určená výchozí hodnota nebude mít žádný efekt, protože platí pro člena, který se používá v kontextech nedovolujících nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyFileFailure"> <source>Error signing output with public key from file '{0}' -- {1}</source> <target state="translated">Chyba při podepisování výstupu pomocí veřejného klíče ze souboru {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_PublicKeyContainerFailure"> <source>Error signing output with public key from container '{0}' -- {1}</source> <target state="translated">Chyba při podepisování výstupu pomocí veřejného klíče z kontejneru {0} -- {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicTypeof"> <source>The typeof operator cannot be used on the dynamic type</source> <target state="translated">Operátor typeof nejde použít na tento dynamický typ.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsDynamicOperation"> <source>An expression tree may not contain a dynamic operation</source> <target state="translated">Strom výrazu nemůže obsahovat dynamickou operaci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncExpressionTree"> <source>Async lambda expressions cannot be converted to expression trees</source> <target state="translated">Asynchronní výrazy lambda nejde převést na stromy výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicAttributeMissing"> <source>Cannot define a class or member that utilizes 'dynamic' because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">Nejde definovat třídu nebo člen, který používá typ dynamic, protože se nedá najít typ {0} požadovaný kompilátorem. Nechybí odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_CannotPassNullForFriendAssembly"> <source>Cannot pass null for friend assembly name</source> <target state="translated">Jako název sestavení typu Friend nejde předat hodnotu Null.</target> <note /> </trans-unit> <trans-unit id="ERR_SignButNoPrivateKey"> <source>Key file '{0}' is missing the private key needed for signing</source> <target state="translated">V souboru klíče {0} chybí privátní klíč potřebný k podepsání.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignButNoKey"> <source>Public signing was specified and requires a public key, but no public key was specified.</source> <target state="translated">Byl určený veřejný podpis, který vyžaduje veřejný klíč, nebyl ale zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_PublicSignNetModule"> <source>Public signing is not supported for netmodules.</source> <target state="translated">Veřejné podepisování netmodulů se nepodporuje.</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="WRN_DelaySignButNoKey_Title"> <source>Delay signing was specified and requires a public key, but no public key was specified</source> <target state="translated">Je určené zpožděné podepsání, které vyžaduje veřejný klíč, ale není zadaný žádný veřejný klíč.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat"> <source>The specified version string does not conform to the required format - major[.minor[.build[.revision]]]</source> <target state="translated">Zadaný řetězec verze není v souladu s požadovaným formátem – hlavní_verze[.dílčí_verze[.build[.revize]]].</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormatDeterministic"> <source>The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation</source> <target state="translated">Zadaný řetězec verze obsahuje zástupné znaky, které nejsou kompatibilní s determinismem. Odeberte zástupné znaky z řetězce verze nebo pro tuto kompilaci zakažte determinismus.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidVersionFormat2"> <source>The specified version string does not conform to the required format - major.minor.build.revision (without wildcards)</source> <target state="translated">Zadaný řetězec verze není v souladu s požadovaným formátem – hlavní_verze.dílčí_verze.build.revize (bez zástupných znaků).</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">Zadaný řetězec verze není v souladu s doporučeným formátem – hlavní_verze.dílčí_verze.build.revize.</target> <note /> </trans-unit> <trans-unit id="WRN_InvalidVersionFormat_Title"> <source>The specified version string does not conform to the recommended format - major.minor.build.revision</source> <target state="translated">Zadaný řetězec verze není v souladu s doporučeným formátem – hlavní_verze.dílčí_verze.build.revize.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCultureForExe"> <source>Executables cannot be satellite assemblies; culture should always be empty</source> <target state="translated">Spustitelné soubory nemůžou být satelitními sestaveními; jazyková verze by vždy měla být prázdná.</target> <note /> </trans-unit> <trans-unit id="ERR_NoCorrespondingArgument"> <source>There is no argument given that corresponds to the required formal parameter '{0}' of '{1}'</source> <target state="translated">Není dán žádný argument, který by odpovídal požadovanému formálnímu parametru {0} v {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch"> <source>The command line switch '{0}' is not yet implemented and was ignored.</source> <target state="translated">Přepínač příkazového řádku {0} ještě není implementovaný, a tak se ignoroval.</target> <note /> </trans-unit> <trans-unit id="WRN_UnimplementedCommandLineSwitch_Title"> <source>Command line switch is not yet implemented</source> <target state="translated">Přepínač příkazového řádku zatím není implementovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_ModuleEmitFailure"> <source>Failed to emit module '{0}': {1}</source> <target state="translated">Nepovedlo se vygenerovat modul {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_FixedLocalInLambda"> <source>Cannot use fixed local '{0}' inside an anonymous method, lambda expression, or query expression</source> <target state="translated">Pevnou lokální proměnnou {0} nejde použít v anonymní metodě, lambda výrazu nebo výrazu dotazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsNamedArgument"> <source>An expression tree may not contain a named argument specification</source> <target state="translated">Strom výrazu nemůže obsahovat specifikaci pojmenovaného argumentu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsOptionalArgument"> <source>An expression tree may not contain a call or invocation that uses optional arguments</source> <target state="translated">Strom výrazu nemůže obsahovat volání, které používá nepovinné argumenty.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsIndexedProperty"> <source>An expression tree may not contain an indexed property</source> <target state="translated">Strom výrazu nemůže obsahovat indexovanou vlastnost.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedPropertyRequiresParams"> <source>Indexed property '{0}' has non-optional arguments which must be provided</source> <target state="translated">Indexovaná vlastnost {0} má argumenty, které nejsou nepovinné a je třeba je zadat.</target> <note /> </trans-unit> <trans-unit id="ERR_IndexedPropertyMustHaveAllOptionalParams"> <source>Indexed property '{0}' must have all arguments optional</source> <target state="translated">Indexovaná vlastnost {0} musí mít všechny argumenty volitelné.</target> <note /> </trans-unit> <trans-unit id="ERR_SpecialByRefInLambda"> <source>Instance of type '{0}' cannot be used inside a nested function, query expression, iterator block or async method</source> <target state="translated">Instance typu {0} nelze použít uvnitř vnořené funkce, výrazu dotazu, bloku iterátoru nebo asynchronní metody.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeMissingAction"> <source>First argument to a security attribute must be a valid SecurityAction</source> <target state="translated">První argument atributu zabezpečení musí být platný SecurityAction.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidAction"> <source>Security attribute '{0}' has an invalid SecurityAction value '{1}'</source> <target state="translated">Atribut zabezpečení {0} má neplatnou hodnotu SecurityAction {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionAssembly"> <source>SecurityAction value '{0}' is invalid for security attributes applied to an assembly</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidActionTypeOrMethod"> <source>SecurityAction value '{0}' is invalid for security attributes applied to a type or a method</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atributy zabezpečení použité u typu nebo metody.</target> <note /> </trans-unit> <trans-unit id="ERR_PrincipalPermissionInvalidAction"> <source>SecurityAction value '{0}' is invalid for PrincipalPermission attribute</source> <target state="translated">Hodnota SecurityAction {0} není platná pro atribut PrincipalPermission.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotValidInExpressionTree"> <source>An expression tree may not contain '{0}'</source> <target state="translated">Strom výrazu nesmí obsahovat {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeInvalidFile"> <source>Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute</source> <target state="translated">Nejde vyřešit cestu k souboru {0} zadanému pro pojmenovaný argument {1} pro atribut PermissionSet.</target> <note /> </trans-unit> <trans-unit id="ERR_PermissionSetAttributeFileReadError"> <source>Error reading file '{0}' specified for the named argument '{1}' for PermissionSet attribute: '{2}'</source> <target state="translated">Chyba při čtení souboru {0} zadaného pro pojmenovaný argument {1} pro atribut PermissionSet: {2}</target> <note /> </trans-unit> <trans-unit id="ERR_GlobalSingleTypeNameNotFoundFwd"> <source>The type name '{0}' could not be found in the global namespace. This type has been forwarded to assembly '{1}' Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nepovedlo najít v globálním oboru názvů. Tento typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_DottedTypeNameNotFoundInNSFwd"> <source>The type name '{0}' could not be found in the namespace '{1}'. This type has been forwarded to assembly '{2}' Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nepovedlo najít v oboru názvů {1}. Tento typ se předal do sestavení {2}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleTypeNameNotFoundFwd"> <source>The type name '{0}' could not be found. This type has been forwarded to assembly '{1}'. Consider adding a reference to that assembly.</source> <target state="translated">Název typu {0} se nenašel. Typ se předal do sestavení {1}. Zvažte přidání odkazu do tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_AssemblySpecifiedForLinkAndRef"> <source>Assemblies '{0}' and '{1}' refer to the same metadata but only one is a linked reference (specified using /link option); consider removing one of the references.</source> <target state="translated">Sestavení {0} a {1} odkazují na stejná metadata, ale jenom v jednom případě je to propojený odkaz (zadaný s možností /link). Zvažte odebrání jednoho z odkazů.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAdd"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete.</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAdd_Title"> <source>The best overloaded Add method for the collection initializer element is obsolete</source> <target state="translated">Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAddStr"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1}</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1}</target> <note /> </trans-unit> <trans-unit id="WRN_DeprecatedCollectionInitAddStr_Title"> <source>The best overloaded Add method for the collection initializer element is obsolete</source> <target state="translated">Optimální přetěžovaná metoda Add pro element inicializátoru kolekce je zastaralá.</target> <note /> </trans-unit> <trans-unit id="ERR_DeprecatedCollectionInitAddStr"> <source>The best overloaded Add method '{0}' for the collection initializer element is obsolete. {1}</source> <target state="translated">Optimální přetěžovaná metoda Add {0} pro element inicializátoru kolekce je zastaralá. {1}</target> <note /> </trans-unit> <trans-unit id="ERR_SecurityAttributeInvalidTarget"> <source>Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations.</source> <target state="translated">Atribut zabezpečení {0} není platný u tohoto typu deklarace. Atributy zabezpečení jsou platné jenom u deklarací sestavení, typu a metody.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArg"> <source>Cannot use an expression of type '{0}' as an argument to a dynamically dispatched operation.</source> <target state="translated">Nejde použít výraz typu {0} jako argument pro dynamicky volanou operaci.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArgLambda"> <source>Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.</source> <target state="translated">Výraz lambda nejde použít jako argument dynamicky volané operace, aniž byste ho nejprve použili na typy delegát nebo strom výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicMethodArgMemgrp"> <source>Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method?</source> <target state="translated">Skupinu metod nejde použít jako argument v dynamicky volané operaci. Měli jste v úmyslu tuto metodu vyvolat?</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBase"> <source>The call to method '{0}' needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.</source> <target state="translated">Volání do metody {0} je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte přetypování dynamických argumentů nebo eliminaci základního přístupu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDynamicQuery"> <source>Query expressions over source type 'dynamic' or with a join sequence of type 'dynamic' are not allowed</source> <target state="translated">Výrazy dotazů se zdrojovým typem dynamic nebo se spojenou sekvencí typu dynamic nejsou povolené.</target> <note /> </trans-unit> <trans-unit id="ERR_NoDynamicPhantomOnBaseIndexer"> <source>The indexer access needs to be dynamically dispatched, but cannot be because it is part of a base access expression. Consider casting the dynamic arguments or eliminating the base access.</source> <target state="translated">Přístup indexeru je nutné volat dynamicky, což ale není možné, protože je součástí výrazu základního přístupu. Zvažte použití dynamických argumentů nebo eliminaci základního přístupu.</target> <note /> </trans-unit> <trans-unit id="WRN_DynamicDispatchToConditionalMethod"> <source>The dynamically dispatched call to method '{0}' may fail at runtime because one or more applicable overloads are conditional methods.</source> <target state="translated">Dynamicky volané volání do metody {0} se za běhu nemusí zdařit, protože nejmíň jedno použitelné přetížení je podmíněná metoda.</target> <note /> </trans-unit> <trans-unit id="WRN_DynamicDispatchToConditionalMethod_Title"> <source>Dynamically dispatched call may fail at runtime because one or more applicable overloads are conditional methods</source> <target state="translated">Dynamicky volané volání může za běhu selhat, protože nejmíň jedno použitelné přetížení představuje podmíněnou metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadArgTypeDynamicExtension"> <source>'{0}' has no applicable method named '{1}' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.</source> <target state="translated">{0} nemá žádnou použitelnou metodu s názvem {1}, ale zřejmě má metodu rozšíření s tímto názvem. Metody rozšíření se nedají volat dynamicky. Zvažte použití dynamických argumentů nebo volání metody rozšíření bez syntaxe metody rozšíření.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerMemberName"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerFilePathAttribute.</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerFilePathPreferredOverCallerMemberName_Title"> <source>The CallerMemberNameAttribute will have no effect; it is overridden by the CallerFilePathAttribute</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerFilePathAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerMemberName"> <source>The CallerMemberNameAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="translated">CallerMemberNameAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerMemberName_Title"> <source>The CallerMemberNameAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="translated">CallerMemberNameAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerFilePath"> <source>The CallerFilePathAttribute applied to parameter '{0}' will have no effect. It is overridden by the CallerLineNumberAttribute.</source> <target state="translated">CallerFilePathAttribute použitý u parametru {0} nebude mít žádný účinek. Přepíše ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="WRN_CallerLineNumberPreferredOverCallerFilePath_Title"> <source>The CallerFilePathAttribute will have no effect; it is overridden by the CallerLineNumberAttribute</source> <target state="translated">CallerFilePathAttribute nebude mít žádný efekt. Přepisuje ho CallerLineNumberAttribute.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDynamicCondition"> <source>Expression must be implicitly convertible to Boolean or its type '{0}' must define operator '{1}'.</source> <target state="translated">Výraz musí být implicitně převeditelný na logickou hodnotu nebo její typ {0} musí definovat operátor {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MixingWinRTEventWithRegular"> <source>'{0}' cannot implement '{1}' because '{2}' is a Windows Runtime event and '{3}' is a regular .NET event.</source> <target state="translated">{0} nemůže implementovat {1}, protože {2} je událost Windows Runtimu a {3} je normální událost .NET.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope1"> <source>Call System.IDisposable.Dispose() on allocated instance of {0} before all references to it are out of scope.</source> <target state="translated">Vyvolejte System.IDisposable.Dispose() na přidělenou instanci {0} dřív, než budou všechny odkazy na ni mimo obor.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope1_Title"> <source>Call System.IDisposable.Dispose() on allocated instance before all references to it are out of scope</source> <target state="translated">Vyvolejte System.IDisposable.Dispose() u přidělené instance, než budou všechny odkazy na ni mimo rozsah.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope2"> <source>Allocated instance of {0} is not disposed along all exception paths. Call System.IDisposable.Dispose() before all references to it are out of scope.</source> <target state="translated">Přidělená instance {0} se neuvolní v průběhu všech cest výjimky. Vyvolejte System.IDisposable.Dispose() dřív, než budou všechny odkazy na ni mimo obor.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2000_DisposeObjectsBeforeLosingScope2_Title"> <source>Allocated instance is not disposed along all exception paths</source> <target state="translated">Přidělená instance není uvolněná v průběhu všech cest výjimek.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2202_DoNotDisposeObjectsMultipleTimes"> <source>Object '{0}' can be disposed more than once.</source> <target state="translated">Objekt {0} se dá uvolnit víc než jednou.</target> <note /> </trans-unit> <trans-unit id="WRN_CA2202_DoNotDisposeObjectsMultipleTimes_Title"> <source>Object can be disposed more than once</source> <target state="translated">Objekt se dá uvolnit víc než jednou.</target> <note /> </trans-unit> <trans-unit id="ERR_NewCoClassOnLink"> <source>Interop type '{0}' cannot be embedded. Use the applicable interface instead.</source> <target state="translated">Typ spolupráce {0} nemůže být vložený. Místo něho použijte použitelné rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIANestedType"> <source>Type '{0}' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože je vnořeným typem. Zvažte nastavení vlastnosti Vložit typy spolupráce na false.</target> <note /> </trans-unit> <trans-unit id="ERR_GenericsUsedInNoPIAType"> <source>Type '{0}' cannot be embedded because it has a generic argument. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Typ {0} nemůže být vložený, protože má obecný argument. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropStructContainsMethods"> <source>Embedded interop struct '{0}' can contain only public instance fields.</source> <target state="translated">Vložená struktura spolupráce {0} může obsahovat jenom veřejné položky instance.</target> <note /> </trans-unit> <trans-unit id="ERR_WinRtEventPassedByRef"> <source>A Windows Runtime event may not be passed as an out or ref parameter.</source> <target state="translated">Událost Windows Runtimu se nesmí předat jako parametr out nebo ref.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingMethodOnSourceInterface"> <source>Source interface '{0}' is missing method '{1}' which is required to embed event '{2}'.</source> <target state="translated">Zdrojovému rozhraní {0} chybí metoda {1}, která se vyžaduje pro vložení události {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingSourceInterface"> <source>Interface '{0}' has an invalid source interface which is required to embed event '{1}'.</source> <target state="translated">Rozhraní {0} má neplatné zdrojové rozhraní, které se vyžaduje pro vložení události {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropTypeMissingAttribute"> <source>Interop type '{0}' cannot be embedded because it is missing the required '{1}' attribute.</source> <target state="translated">Typ spolupráce {0} nemůže být vložený, protože postrádá požadovaný atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAssemblyMissingAttribute"> <source>Cannot embed interop types from assembly '{0}' because it is missing the '{1}' attribute.</source> <target state="translated">Nejde vložit typy spolupráce pro sestavení {0}, protože postrádá atribut {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_NoPIAAssemblyMissingAttributes"> <source>Cannot embed interop types from assembly '{0}' because it is missing either the '{1}' attribute or the '{2}' attribute.</source> <target state="translated">Nejde vložit typy spolupráce ze sestavení {0}, protože postrádá buď atribut {1}, nebo atribut {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_InteropTypesWithSameNameAndGuid"> <source>Cannot embed interop type '{0}' found in both assembly '{1}' and '{2}'. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Nejde vložit typ spolupráce {0} nalezený v sestavení {1} i {2}. Zvažte nastavení vlastnosti Vložit typy spolupráce na hodnotu false.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalTypeNameClash"> <source>Embedding the interop type '{0}' from assembly '{1}' causes a name clash in the current assembly. Consider setting the 'Embed Interop Types' property to false.</source> <target state="translated">Vložení typu spolupráce {0} ze sestavení {1} způsobí konflikt názvů v aktuálním sestavení. Zvažte nastavení vlastnosti Vložit typy spolupráce na false.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA"> <source>A reference was created to embedded interop assembly '{0}' because of an indirect reference to that assembly created by assembly '{1}'. Consider changing the 'Embed Interop Types' property on either assembly.</source> <target state="translated">Vytvořil se odkaz na vložené sestavení vzájemné spolupráce {0}, protože existuje nepřímý odkaz na toto sestavení ze sestavení {1}. Zvažte změnu vlastnosti Vložit typy vzájemné spolupráce u obou sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA_Title"> <source>A reference was created to embedded interop assembly because of an indirect assembly reference</source> <target state="translated">Byl vytvořený odkaz na vložené definiční sestavení z důvodu nepřímého odkazu na toto sestavení.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyReferencesLinkedPIA_Description"> <source>You have added a reference to an assembly using /link (Embed Interop Types property set to True). This instructs the compiler to embed interop type information from that assembly. However, the compiler cannot embed interop type information from that assembly because another assembly that you have referenced also references that assembly using /reference (Embed Interop Types property set to False). To embed interop type information for both assemblies, use /link for references to each assembly (set the Embed Interop Types property to True). To remove the warning, you can use /reference instead (set the Embed Interop Types property to False). In this case, a primary interop assembly (PIA) provides interop type information.</source> <target state="translated">Přidali jste odkaz na sestavení pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). Tím se kompilátoru dává instrukce, aby vložil informace o typech spolupráce z tohoto sestavení. Kompilátor ale nemůže tyto informace z tohoto sestavení vložit, protože jiné sestavení, na které jste nastavili odkaz, odkazuje taky na toto sestavení, a to pomocí parametru /reference (vlastnost Přibalit definované typy nastavená na False). Pokud chcete vložit informace o typech spolupráce pro obě sestavení, odkazujte na každé z nich pomocí parametru /link (vlastnost Přibalit definované typy nastavená na True). Pokud chcete odstranit toto varování, můžete místo toho použít /reference (vlastnost Přibalit definované typy nastavená na False). V tomto případě uvedené informace poskytne primární definiční sestavení (PIA).</target> <note /> </trans-unit> <trans-unit id="ERR_GenericsUsedAcrossAssemblies"> <source>Type '{0}' from assembly '{1}' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.</source> <target state="translated">Typ {0} ze sestavení {1} se nedá použít přes hranice sestavení, protože má argument obecného typu, který je vloženým definičním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_NoCanonicalView"> <source>Cannot find the interop type that matches the embedded interop type '{0}'. Are you missing an assembly reference?</source> <target state="translated">Nejde najít typ spolupráce, který odpovídá vloženému typu {0}. Nechybí odkaz na sestavení?</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMismatch"> <source>Module name '{0}' stored in '{1}' must match its filename.</source> <target state="translated">Název modulu {0} uložený v {1} musí odpovídat svému názvu souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_BadModuleName"> <source>Invalid module name: {0}</source> <target state="translated">Neplatný název modulu: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadCompilationOptionValue"> <source>Invalid '{0}' value: '{1}'.</source> <target state="translated">Neplatná hodnota {0}: {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAppConfigPath"> <source>AppConfigPath must be absolute.</source> <target state="translated">AppConfigPath musí být absolutní.</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden"> <source>Attribute '{0}' from module '{1}' will be ignored in favor of the instance appearing in source</source> <target state="translated">Atribut {0} z modulu {1} se bude ignorovat ve prospěch instance, která se objeví ve zdroji.</target> <note /> </trans-unit> <trans-unit id="WRN_AssemblyAttributeFromModuleIsOverridden_Title"> <source>Attribute will be ignored in favor of the instance appearing in source</source> <target state="translated">Atribut se bude ignorovat ve prospěch instance zobrazené ve zdroji.</target> <note /> </trans-unit> <trans-unit id="ERR_CmdOptionConflictsSource"> <source>Attribute '{0}' given in a source file conflicts with option '{1}'.</source> <target state="translated">Atribut {0} daný ve zdrojovém souboru je v konfliktu s možností {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_FixedBufferTooManyDimensions"> <source>A fixed buffer may only have one dimension.</source> <target state="translated">Pevná vyrovnávací paměť může mít jen jednu dimenzi.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName"> <source>Referenced assembly '{0}' does not have a strong name.</source> <target state="translated">Odkazované sestavení {0} nemá silný název.</target> <note /> </trans-unit> <trans-unit id="WRN_ReferencedAssemblyDoesNotHaveStrongName_Title"> <source>Referenced assembly does not have a strong name</source> <target state="translated">Odkazované sestavení nemá silný název.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidSignaturePublicKey"> <source>Invalid signature public key specified in AssemblySignatureKeyAttribute.</source> <target state="translated">V atributu AssemblySignatureKeyAttribute je uvedený neplatný veřejný klíč podpisu.</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypeConflictsWithDeclaration"> <source>Type '{0}' exported from module '{1}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">Typ {0} exportovaný z modulu {1} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_ExportedTypesConflict"> <source>Type '{0}' exported from module '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">Typ {0} exportovaný z modulu {1} je v konfliktu s typem {2} exportovaným z modulu {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithDeclaration"> <source>Forwarded type '{0}' conflicts with type declared in primary module of this assembly.</source> <target state="translated">Předaný typ {0} je v konfliktu s typem deklarovaným v primárním modulu tohoto sestavení.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypesConflict"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' forwarded to assembly '{3}'.</source> <target state="translated">Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} předaným do sestavení {3}.</target> <note /> </trans-unit> <trans-unit id="ERR_ForwardedTypeConflictsWithExportedType"> <source>Type '{0}' forwarded to assembly '{1}' conflicts with type '{2}' exported from module '{3}'.</source> <target state="translated">Typ {0} předaný do sestavení {1} je v konfliktu s typem {2} exportovaným z modulu {3}.</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch"> <source>Referenced assembly '{0}' has different culture setting of '{1}'.</source> <target state="translated">Odkazované sestavení {0} má jiné nastavení jazykové verze {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_RefCultureMismatch_Title"> <source>Referenced assembly has different culture setting</source> <target state="translated">Odkazované sestavení má jiné nastavení jazykové verze.</target> <note /> </trans-unit> <trans-unit id="ERR_AgnosticToMachineModule"> <source>Agnostic assembly cannot have a processor specific module '{0}'.</source> <target state="translated">Agnostické sestavení nemůže mít modul {0} určený pro konkrétní procesor.</target> <note /> </trans-unit> <trans-unit id="ERR_ConflictingMachineModule"> <source>Assembly and module '{0}' cannot target different processors.</source> <target state="translated">Sestavení a modul {0} nemůžou mířit na různé procesory.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly"> <source>Referenced assembly '{0}' targets a different processor.</source> <target state="translated">Odkazované sestavení {0} míří na jiný procesor.</target> <note /> </trans-unit> <trans-unit id="WRN_ConflictingMachineAssembly_Title"> <source>Referenced assembly targets a different processor</source> <target state="translated">Odkazované sestavení míří na jiný procesor.</target> <note /> </trans-unit> <trans-unit id="ERR_CryptoHashFailed"> <source>Cryptographic failure while creating hashes.</source> <target state="translated">Při vytváření čísel hash došlo ke kryptografické chybě.</target> <note /> </trans-unit> <trans-unit id="ERR_MissingNetModuleReference"> <source>Reference to '{0}' netmodule missing.</source> <target state="translated">Chybí odkaz na netmodule {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_NetModuleNameMustBeUnique"> <source>Module '{0}' is already defined in this assembly. Each module must have a unique filename.</source> <target state="translated">Modul {0} je už v tomto sestavení definovaný. Každý modul musí mít jedinečný název souboru.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadConfigFile"> <source>Cannot read config file '{0}' -- '{1}'</source> <target state="translated">Nejde přečíst konfigurační soubor {0} -- {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_EncNoPIAReference"> <source>Cannot continue since the edit includes a reference to an embedded type: '{0}'.</source> <target state="translated">Nedá se pokračovat, protože úprava obsahuje odkaz na vložený typ: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_EncReferenceToAddedMember"> <source>Member '{0}' added during the current debug session can only be accessed from within its declaring assembly '{1}'.</source> <target state="translated">Ke členu {0} přidanému během aktuální relace ladění se dá přistupovat jenom z jeho deklarovaného sestavení {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MutuallyExclusiveOptions"> <source>Compilation options '{0}' and '{1}' can't both be specified at the same time.</source> <target state="translated">Možnosti kompilace {0} a {1} se nedají zadat současně.</target> <note /> </trans-unit> <trans-unit id="ERR_LinkedNetmoduleMetadataMustProvideFullPEImage"> <source>Linked netmodule metadata must provide a full PE image: '{0}'.</source> <target state="translated">Propojená metadata netmodule musí poskytovat plnou image PE: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadPrefer32OnLib"> <source>/platform:anycpu32bitpreferred can only be used with /t:exe, /t:winexe and /t:appcontainerexe</source> <target state="translated">Možnost /platform:anycpu32bitpreferred jde použít jenom s možnostmi /t:exe, /t:winexe a /t:appcontainerexe.</target> <note /> </trans-unit> <trans-unit id="IDS_PathList"> <source>&lt;path list&gt;</source> <target state="translated">&lt;seznam cest&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_Text"> <source>&lt;text&gt;</source> <target state="translated">&lt;text&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNullPropagatingOperator"> <source>null propagating operator</source> <target state="translated">operátor šířící null</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedMethod"> <source>expression-bodied method</source> <target state="translated">metoda s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedProperty"> <source>expression-bodied property</source> <target state="translated">vlastnost s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureExpressionBodiedIndexer"> <source>expression-bodied indexer</source> <target state="translated">indexer s výrazem v těle</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAutoPropertyInitializer"> <source>auto property initializer</source> <target state="translated">automatický inicializátor vlastnosti</target> <note /> </trans-unit> <trans-unit id="IDS_Namespace1"> <source>&lt;namespace&gt;</source> <target state="translated">&lt;obor názvů&gt;</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefLocalsReturns"> <source>byref locals and returns</source> <target state="translated">lokální proměnné a vrácení podle odkazu</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureReadOnlyReferences"> <source>readonly references</source> <target state="translated">odkazy jen pro čtení</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefStructs"> <source>ref structs</source> <target state="translated">struktury REF</target> <note /> </trans-unit> <trans-unit id="CompilationC"> <source>Compilation (C#): </source> <target state="translated">Kompilace (C#): </target> <note /> </trans-unit> <trans-unit id="SyntaxNodeIsNotWithinSynt"> <source>Syntax node is not within syntax tree</source> <target state="translated">Uzel syntaxe není ve stromu syntaxe.</target> <note /> </trans-unit> <trans-unit id="LocationMustBeProvided"> <source>Location must be provided in order to provide minimal type qualification.</source> <target state="translated">Musí být zadané umístění, aby se zajistila minimální kvalifikace typu.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeSemanticModelMust"> <source>SyntaxTreeSemanticModel must be provided in order to provide minimal type qualification.</source> <target state="translated">Musí být zadaný SyntaxTreeSemanticModel, aby se zajistila minimální kvalifikace typu.</target> <note /> </trans-unit> <trans-unit id="CantReferenceCompilationOf"> <source>Can't reference compilation of type '{0}' from {1} compilation.</source> <target state="translated">Na kompilaci typu {0} nejde odkazovat z kompilace {1}.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeAlreadyPresent"> <source>Syntax tree already present</source> <target state="translated">Strom syntaxe už je přítomný.</target> <note /> </trans-unit> <trans-unit id="SubmissionCanOnlyInclude"> <source>Submission can only include script code.</source> <target state="translated">Odeslání může zahrnovat jenom kód skriptu.</target> <note /> </trans-unit> <trans-unit id="SubmissionCanHaveAtMostOne"> <source>Submission can have at most one syntax tree.</source> <target state="translated">Odeslání musí mít aspoň jeden strom syntaxe.</target> <note /> </trans-unit> <trans-unit id="TreeMustHaveARootNodeWith"> <source>tree must have a root node with SyntaxKind.CompilationUnit</source> <target state="translated">strom musí mít kořenový uzel s prvkem SyntaxKind.CompilationUnit</target> <note /> </trans-unit> <trans-unit id="TypeArgumentCannotBeNull"> <source>Type argument cannot be null</source> <target state="translated">Argument typu nemůže být null.</target> <note /> </trans-unit> <trans-unit id="WrongNumberOfTypeArguments"> <source>Wrong number of type arguments</source> <target state="translated">Chybný počet argumentů typu</target> <note /> </trans-unit> <trans-unit id="NameConflictForName"> <source>Name conflict for name {0}</source> <target state="translated">Konflikt u názvu {0}</target> <note /> </trans-unit> <trans-unit id="LookupOptionsHasInvalidCombo"> <source>LookupOptions has an invalid combination of options</source> <target state="translated">LookupOptions má neplatnou kombinaci možností.</target> <note /> </trans-unit> <trans-unit id="ItemsMustBeNonEmpty"> <source>items: must be non-empty</source> <target state="translated">Položky: Nesmí být prázdné.</target> <note /> </trans-unit> <trans-unit id="UseVerbatimIdentifier"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier or Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier to create identifier tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Identifier nebo Microsoft.CodeAnalysis.CSharp.SyntaxFactory.VerbatimIdentifier můžete vytvořit tokeny identifikátorů.</target> <note /> </trans-unit> <trans-unit id="UseLiteralForTokens"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create character literal tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit znakové literálové tokeny.</target> <note /> </trans-unit> <trans-unit id="UseLiteralForNumeric"> <source>Use Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal to create numeric literal tokens.</source> <target state="translated">Pomocí Microsoft.CodeAnalysis.CSharp.SyntaxFactory.Literal můžete vytvořit numerické literálové tokeny.</target> <note /> </trans-unit> <trans-unit id="ThisMethodCanOnlyBeUsedToCreateTokens"> <source>This method can only be used to create tokens - {0} is not a token kind.</source> <target state="translated">Tato metoda se dá používat jenom k vytváření tokenů – {0} není druh tokenu.</target> <note /> </trans-unit> <trans-unit id="GenericParameterDefinition"> <source>Generic parameter is definition when expected to be reference {0}</source> <target state="translated">Obecný parametr je definice, i když se očekával odkaz {0}.</target> <note /> </trans-unit> <trans-unit id="InvalidGetDeclarationNameMultipleDeclarators"> <source>Called GetDeclarationName for a declaration node that can possibly contain multiple variable declarators.</source> <target state="translated">Proběhlo volání funkce GetDeclarationName kvůli uzlu deklarací, který by mohl obsahovat několik variabilních deklarátorů.</target> <note /> </trans-unit> <trans-unit id="TreeNotPartOfCompilation"> <source>tree not part of compilation</source> <target state="translated">strom není součástí kompilace</target> <note /> </trans-unit> <trans-unit id="PositionIsNotWithinSyntax"> <source>Position is not within syntax tree with full span {0}</source> <target state="translated">Pozice není v rámci stromu syntaxe s plným rozpětím {0}.</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang"> <source>The language name '{0}' is invalid.</source> <target state="translated">Název jazyka {0} je neplatný.</target> <note /> </trans-unit> <trans-unit id="WRN_BadUILang_Title"> <source>The language name is invalid</source> <target state="translated">Název jazyka je neplatný.</target> <note /> </trans-unit> <trans-unit id="ERR_UnsupportedTransparentIdentifierAccess"> <source>Transparent identifier member access failed for field '{0}' of '{1}'. Does the data being queried implement the query pattern?</source> <target state="translated">U pole {0} v {1} selhal přístup pro členy s transparentním identifikátorem. Implementují dotazovaná data vzor dotazu?</target> <note /> </trans-unit> <trans-unit id="ERR_ParamDefaultValueDiffersFromAttribute"> <source>The parameter has multiple distinct default values.</source> <target state="translated">Parametr má víc odlišných výchozích hodnot.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldHasMultipleDistinctConstantValues"> <source>The field has multiple distinct constant values.</source> <target state="translated">Pole má víc odlišných konstantních hodnot.</target> <note /> </trans-unit> <trans-unit id="WRN_UnqualifiedNestedTypeInCref"> <source>Within cref attributes, nested types of generic types should be qualified.</source> <target state="translated">V atributech cref by měly být kvalifikované vnořené typy obecných typů.</target> <note /> </trans-unit> <trans-unit id="WRN_UnqualifiedNestedTypeInCref_Title"> <source>Within cref attributes, nested types of generic types should be qualified</source> <target state="translated">V atributech cref by měly být kvalifikované vnořené typy obecných typů.</target> <note /> </trans-unit> <trans-unit id="NotACSharpSymbol"> <source>Not a C# symbol.</source> <target state="translated">Nepředstavuje symbol C#.</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedUsingDirective"> <source>Unnecessary using directive.</source> <target state="translated">Nepotřebná direktiva using</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedExternAlias"> <source>Unused extern alias.</source> <target state="translated">Nepoužívaný alias extern</target> <note /> </trans-unit> <trans-unit id="ElementsCannotBeNull"> <source>Elements cannot be null.</source> <target state="translated">Elementy nemůžou mít hodnotu null.</target> <note /> </trans-unit> <trans-unit id="IDS_LIB_ENV"> <source>LIB environment variable</source> <target state="translated">proměnná prostředí LIB</target> <note /> </trans-unit> <trans-unit id="IDS_LIB_OPTION"> <source>/LIB option</source> <target state="translated">parametr /LIB</target> <note /> </trans-unit> <trans-unit id="IDS_REFERENCEPATH_OPTION"> <source>/REFERENCEPATH option</source> <target state="translated">Možnost /REFERENCEPATH</target> <note /> </trans-unit> <trans-unit id="IDS_DirectoryDoesNotExist"> <source>directory does not exist</source> <target state="translated">adresář neexistuje</target> <note /> </trans-unit> <trans-unit id="IDS_DirectoryHasInvalidPath"> <source>path is too long or invalid</source> <target state="translated">cesta je moc dlouhá nebo neplatná.</target> <note /> </trans-unit> <trans-unit id="WRN_NoRuntimeMetadataVersion"> <source>No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.</source> <target state="translated">Nenašla se žádná hodnota RuntimeMetadataVersion, žádné sestavení obsahující System.Object ani nebyla v možnostech zadaná hodnota pro RuntimeMetadataVersion.</target> <note /> </trans-unit> <trans-unit id="WRN_NoRuntimeMetadataVersion_Title"> <source>No value for RuntimeMetadataVersion found</source> <target state="translated">Nenašla se žádná hodnota pro RuntimeMetadataVersion.</target> <note /> </trans-unit> <trans-unit id="WrongSemanticModelType"> <source>Expected a {0} SemanticModel.</source> <target state="translated">Očekával se SemanticModel {0}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLambda"> <source>lambda expression</source> <target state="translated">výraz lambda</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion1"> <source>Feature '{0}' is not available in C# 1. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 1. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion2"> <source>Feature '{0}' is not available in C# 2. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 2. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion3"> <source>Feature '{0}' is not available in C# 3. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 3. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion4"> <source>Feature '{0}' is not available in C# 4. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 4. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion5"> <source>Feature '{0}' is not available in C# 5. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 5. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion6"> <source>Feature '{0}' is not available in C# 6. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 6. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7"> <source>Feature '{0}' is not available in C# 7.0. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.0. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="IDS_VersionExperimental"> <source>'experimental'</source> <target state="translated">'"experimentální"</target> <note /> </trans-unit> <trans-unit id="PositionNotWithinTree"> <source>Position must be within span of the syntax tree.</source> <target state="translated">Pozice musí být v rozpětí stromu syntaxe.</target> <note /> </trans-unit> <trans-unit id="SpeculatedSyntaxNodeCannotBelongToCurrentCompilation"> <source>Syntax node to be speculated cannot belong to a syntax tree from the current compilation.</source> <target state="translated">Uzel syntaxe určený ke spekulaci nemůže patřit do stromu syntaxe z aktuální kompilace.</target> <note /> </trans-unit> <trans-unit id="ChainingSpeculativeModelIsNotSupported"> <source>Chaining speculative semantic model is not supported. You should create a speculative model from the non-speculative ParentModel.</source> <target state="translated">Zřetězení spekulativního sémantického modelu se nepodporuje. Měli byste vytvořit spekulativní model z nespekulativního modelu ParentModel.</target> <note /> </trans-unit> <trans-unit id="IDS_ToolName"> <source>Microsoft (R) Visual C# Compiler</source> <target state="translated">Kompilátor Microsoft (R) Visual C#</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine1"> <source>{0} version {1}</source> <target state="translated">{0} verze {1}</target> <note /> </trans-unit> <trans-unit id="IDS_LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. Všechna práva vyhrazena.</target> <note /> </trans-unit> <trans-unit id="IDS_LangVersions"> <source>Supported language versions:</source> <target state="translated">Podporované jazykové verze:</target> <note /> </trans-unit> <trans-unit id="ERR_ComImportWithInitializers"> <source>'{0}': a class with the ComImport attribute cannot specify field initializers.</source> <target state="translated">{0}: Třída s atributem ComImport nemůže určovat inicializátory polí.</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong"> <source>Local name '{0}' is too long for PDB. Consider shortening or compiling without /debug.</source> <target state="translated">Místní název {0} je moc dlouhý pro PDB. Zvažte jeho zkrácení nebo kompilaci bez /debug.</target> <note /> </trans-unit> <trans-unit id="WRN_PdbLocalNameTooLong_Title"> <source>Local name is too long for PDB</source> <target state="translated">Lokální název je moc dlouhý pro PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_RetNoObjectRequiredLambda"> <source>Anonymous function converted to a void returning delegate cannot return a value</source> <target state="translated">Anonymní funkce převedená na void, která vrací delegáta, nemůže vracet hodnotu.</target> <note /> </trans-unit> <trans-unit id="ERR_TaskRetNoObjectRequiredLambda"> <source>Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task&lt;T&gt;'?</source> <target state="translated">Asynchronní lambda výraz převedený na Task a vracející delegáta nemůže vrátit hodnotu. Měli jste v úmyslu vrátit Task&lt;T&gt;?</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated"> <source>An instance of analyzer {0} cannot be created from {1} : {2}.</source> <target state="translated">Instance analyzátoru {0} nejde vytvořit z {1} : {2}.</target> <note /> </trans-unit> <trans-unit id="WRN_AnalyzerCannotBeCreated_Title"> <source>An analyzer instance cannot be created</source> <target state="translated">Nedá se vytvořit instance analyzátoru.</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly"> <source>The assembly {0} does not contain any analyzers.</source> <target state="translated">Sestavení {0} neobsahuje žádné analyzátory.</target> <note /> </trans-unit> <trans-unit id="WRN_NoAnalyzerInAssembly_Title"> <source>Assembly does not contain any analyzers</source> <target state="translated">Sestavení neobsahuje žádné analyzátory.</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer"> <source>Unable to load Analyzer assembly {0} : {1}</source> <target state="translated">Nejde načíst sestavení analyzátoru {0} : {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_UnableToLoadAnalyzer_Title"> <source>Unable to load Analyzer assembly</source> <target state="translated">Nejde načíst sestavení analyzátoru.</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer"> <source>Skipping some types in analyzer assembly {0} due to a ReflectionTypeLoadException : {1}.</source> <target state="translated">Přeskočí se některé typy v sestavení analyzátoru {0} kvůli výjimce ReflectionTypeLoadException: {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CantReadRulesetFile"> <source>Error reading ruleset file {0} - {1}</source> <target state="translated">Chyba při čtení souboru sady pravidel {0} - {1}</target> <note /> </trans-unit> <trans-unit id="ERR_BadPdbData"> <source>Error reading debug information for '{0}'</source> <target state="translated">Chyba při čtení informací ladění pro {0}</target> <note /> </trans-unit> <trans-unit id="IDS_OperationCausedStackOverflow"> <source>Operation caused a stack overflow.</source> <target state="translated">Operace způsobila přetečení zásobníku.</target> <note /> </trans-unit> <trans-unit id="WRN_IdentifierOrNumericLiteralExpected"> <source>Expected identifier or numeric literal.</source> <target state="translated">Očekával se identifikátor nebo číselný literál.</target> <note /> </trans-unit> <trans-unit id="WRN_IdentifierOrNumericLiteralExpected_Title"> <source>Expected identifier or numeric literal</source> <target state="translated">Očekával se identifikátor nebo číselný literál.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerOnNonAutoProperty"> <source>Only auto-implemented properties can have initializers.</source> <target state="translated">Jenom automaticky implementované vlastnosti můžou mít inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyMustHaveGetAccessor"> <source>Auto-implemented properties must have get accessors.</source> <target state="translated">Automaticky implementované vlastnosti musí mít přistupující objekty get.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyMustOverrideSet"> <source>Auto-implemented properties must override all accessors of the overridden property.</source> <target state="translated">Automaticky implementované vlastnosti musí přepsat všechny přistupující objekty přepsané vlastnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializerInStructWithoutExplicitConstructor"> <source>Structs without explicit constructors cannot contain members with initializers.</source> <target state="translated">Struktury bez explicitních konstruktorů nemůžou obsahovat členy s inicializátory.</target> <note /> </trans-unit> <trans-unit id="ERR_EncodinglessSyntaxTree"> <source>Cannot emit debug information for a source text without encoding.</source> <target state="translated">Nejde vygenerovat ladicí informace pro zdrojový text bez kódování.</target> <note /> </trans-unit> <trans-unit id="ERR_BlockBodyAndExpressionBody"> <source>Block bodies and expression bodies cannot both be provided.</source> <target state="translated">Nejde zadat těla bloků i těla výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchFallOut"> <source>Control cannot fall out of switch from final case label ('{0}')</source> <target state="translated">Řízení nemůže opustit příkaz switch z posledního příkazu case ('{0}')</target> <note /> </trans-unit> <trans-unit id="ERR_UnexpectedBoundGenericName"> <source>Type arguments are not allowed in the nameof operator.</source> <target state="translated">Argumenty typů nejsou v operátoru nameof povoleny.</target> <note /> </trans-unit> <trans-unit id="ERR_NullPropagatingOpInExpressionTree"> <source>An expression tree lambda may not contain a null propagating operator.</source> <target state="translated">Strom výrazu lambda nesmí obsahovat operátor šířící null.</target> <note /> </trans-unit> <trans-unit id="ERR_DictionaryInitializerInExpressionTree"> <source>An expression tree lambda may not contain a dictionary initializer.</source> <target state="translated">Strom výrazu lambda nesmí obsahovat inicializátor slovníku.</target> <note /> </trans-unit> <trans-unit id="ERR_ExtensionCollectionElementInitializerInExpressionTree"> <source>An extension Add method is not supported for a collection initializer in an expression lambda.</source> <target state="translated">Rozšiřující metoda Add není pro inicializátor kolekce v lambda výrazu podporovaná.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureNameof"> <source>nameof operator</source> <target state="translated">operátor nameof</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDictionaryInitializer"> <source>dictionary initializer</source> <target state="translated">inicializátor slovníku</target> <note /> </trans-unit> <trans-unit id="ERR_UnclosedExpressionHole"> <source>Missing close delimiter '}' for interpolated expression started with '{'.</source> <target state="translated">Chybí uzavírací oddělovač } pro interpolovaný výraz začínající na {.</target> <note /> </trans-unit> <trans-unit id="ERR_SingleLineCommentInExpressionHole"> <source>A single-line comment may not be used in an interpolated string.</source> <target state="translated">V interpolovaném řetězci se nemůže používat jednořádkový komentář.</target> <note /> </trans-unit> <trans-unit id="ERR_InsufficientStack"> <source>An expression is too long or complex to compile</source> <target state="translated">Výraz je pro zkompilování moc dlouhý nebo složitý.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionHasNoName"> <source>Expression does not have a name.</source> <target state="translated">Výraz není pojmenovaný.</target> <note /> </trans-unit> <trans-unit id="ERR_SubexpressionNotInNameof"> <source>Sub-expression cannot be used in an argument to nameof.</source> <target state="translated">Dílčí výraz se jako argument nameof nedá použít.</target> <note /> </trans-unit> <trans-unit id="ERR_AliasQualifiedNameNotAnExpression"> <source>An alias-qualified name is not an expression.</source> <target state="translated">Název kvalifikovaný pomocí aliasu není výraz.</target> <note /> </trans-unit> <trans-unit id="ERR_NameofMethodGroupWithTypeParameters"> <source>Type parameters are not allowed on a method group as an argument to 'nameof'.</source> <target state="translated">Parametry typu se u skupiny metod nedají použít jako argument nameof.</target> <note /> </trans-unit> <trans-unit id="NoNoneSearchCriteria"> <source>SearchCriteria is expected.</source> <target state="translated">Očekává se třída SearchCriteria.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidAssemblyCulture"> <source>Assembly culture strings may not contain embedded NUL characters.</source> <target state="translated">Řetězce jazykové verze sestavení nesmí obsahovat vložené znaky NUL.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureUsingStatic"> <source>using static</source> <target state="translated">using static</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureInterpolatedStrings"> <source>interpolated strings</source> <target state="translated">interpolované řetězce</target> <note /> </trans-unit> <trans-unit id="IDS_AwaitInCatchAndFinally"> <source>await in catch blocks and finally blocks</source> <target state="translated">očekávat v blocích catch a blocích finally</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureBinaryLiteral"> <source>binary literals</source> <target state="translated">binární literály</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureDigitSeparator"> <source>digit separators</source> <target state="translated">oddělovače číslic</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLocalFunctions"> <source>local functions</source> <target state="translated">místní funkce</target> <note /> </trans-unit> <trans-unit id="ERR_UnescapedCurly"> <source>A '{0}' character must be escaped (by doubling) in an interpolated string.</source> <target state="translated">Znak {0} musí být v interpolovaném řetězci uvozený (zdvojeným znakem).</target> <note /> </trans-unit> <trans-unit id="ERR_EscapedCurly"> <source>A '{0}' character may only be escaped by doubling '{0}{0}' in an interpolated string.</source> <target state="translated">V interpolovaném řetězci může být znak {0} uvozený jenom zdvojeným znakem ({0}{0}).</target> <note /> </trans-unit> <trans-unit id="ERR_TrailingWhitespaceInFormatSpecifier"> <source>A format specifier may not contain trailing whitespace.</source> <target state="translated">Specifikátor formátu nesmí na konci obsahovat mezeru.</target> <note /> </trans-unit> <trans-unit id="ERR_EmptyFormatSpecifier"> <source>Empty format specifier.</source> <target state="translated">Prázdný specifikátor formátu</target> <note /> </trans-unit> <trans-unit id="ERR_ErrorInReferencedAssembly"> <source>There is an error in a referenced assembly '{0}'.</source> <target state="translated">V odkazovaném sestavení {0} je chyba.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionOrDeclarationExpected"> <source>Expression or declaration statement expected.</source> <target state="translated">Očekával se příkaz s výrazem nebo deklarací.</target> <note /> </trans-unit> <trans-unit id="ERR_NameofExtensionMethod"> <source>Extension method groups are not allowed as an argument to 'nameof'.</source> <target state="translated">Skupiny metod rozšíření nejsou povolené jako argument pro nameof.</target> <note /> </trans-unit> <trans-unit id="WRN_AlignmentMagnitude"> <source>Alignment value {0} has a magnitude greater than {1} and may result in a large formatted string.</source> <target state="translated">Hodnota zarovnání {0} má velikost větší než {1} a jejím výsledkem může být velký formátovaný řetězec.</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedExternAlias_Title"> <source>Unused extern alias</source> <target state="translated">Nepoužívaný externí alias</target> <note /> </trans-unit> <trans-unit id="HDN_UnusedUsingDirective_Title"> <source>Unnecessary using directive</source> <target state="translated">Nepotřebná direktiva using</target> <note /> </trans-unit> <trans-unit id="INF_UnableToLoadSomeTypesInAnalyzer_Title"> <source>Skip loading types in analyzer assembly that fail due to a ReflectionTypeLoadException</source> <target state="translated">Přeskočí načtení typů v sestavení analyzátoru, které selžou kvůli výjimce ReflectionTypeLoadException.</target> <note /> </trans-unit> <trans-unit id="WRN_AlignmentMagnitude_Title"> <source>Alignment value has a magnitude that may result in a large formatted string</source> <target state="translated">Hodnota zarovnání má velikost, jejímž výsledkem může být velký formátovaný řetězec.</target> <note /> </trans-unit> <trans-unit id="ERR_ConstantStringTooLong"> <source>Length of String constant resulting from concatenation exceeds System.Int32.MaxValue. Try splitting the string into multiple constants.</source> <target state="translated">Délka konstanty String, která je výsledkem zřetězení, překračuje hodnotu System.Int32.MaxValue. Zkuste rozdělit řetězec na více konstant.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleTooFewElements"> <source>Tuple must contain at least two elements.</source> <target state="translated">Řazená kolekce členů musí obsahovat minimálně dva elementy.</target> <note /> </trans-unit> <trans-unit id="ERR_DebugEntryPointNotSourceMethodDefinition"> <source>Debug entry point must be a definition of a method declared in the current compilation.</source> <target state="translated">Vstupní bod ladění musí být definicí metody deklarované v aktuální kompilaci.</target> <note /> </trans-unit> <trans-unit id="ERR_LoadDirectiveOnlyAllowedInScripts"> <source>#load is only allowed in scripts</source> <target state="translated">#load se povoluje jenom ve skriptech</target> <note /> </trans-unit> <trans-unit id="ERR_PPLoadFollowsToken"> <source>Cannot use #load after first token in file</source> <target state="translated">Za prvním tokenem v souboru se nedá použít #load.</target> <note /> </trans-unit> <trans-unit id="CouldNotFindFile"> <source>Could not find file.</source> <target state="translated">Nepovedlo se najít soubor.</target> <note>File path referenced in source (#load) could not be resolved.</note> </trans-unit> <trans-unit id="SyntaxTreeFromLoadNoRemoveReplace"> <source>SyntaxTree resulted from a #load directive and cannot be removed or replaced directly.</source> <target state="translated">SyntaxTree je výsledkem direktivy #load a nedá se odebrat nebo nahradit přímo.</target> <note /> </trans-unit> <trans-unit id="ERR_SourceFileReferencesNotSupported"> <source>Source file references are not supported.</source> <target state="translated">Odkazy na zdrojový soubor se nepodporují.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPathMap"> <source>The pathmap option was incorrectly formatted.</source> <target state="translated">Možnost pathmap nebyla správně naformátovaná.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidReal"> <source>Invalid real literal.</source> <target state="translated">Neplatný literál real</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropertyCannotBeRefReturning"> <source>Auto-implemented properties cannot return by reference</source> <target state="translated">Automaticky implementované vlastnosti nejde vrátit pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefPropertyMustHaveGetAccessor"> <source>Properties which return by reference must have a get accessor</source> <target state="translated">Vlastnosti, které vracejí pomocí odkazu, musí mít přístupový objekt get.</target> <note /> </trans-unit> <trans-unit id="ERR_RefPropertyCannotHaveSetAccessor"> <source>Properties which return by reference cannot have set accessors</source> <target state="translated">Vlastnosti, které vracejí pomocí odkazu, nemůžou mít přístupové objekty set.</target> <note /> </trans-unit> <trans-unit id="ERR_CantChangeRefReturnOnOverride"> <source>'{0}' must match by reference return of overridden member '{1}'</source> <target state="translated">{0} musí odpovídat návratu pomocí odkazu přepsaného člena {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_MustNotHaveRefReturn"> <source>By-reference returns may only be used in methods that return by reference</source> <target state="translated">Vrácení podle odkazu se dají používat jenom v metodách, které vracejí pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_MustHaveRefReturn"> <source>By-value returns may only be used in methods that return by value</source> <target state="translated">Vrácení podle hodnoty se dají používat jenom v metodách, které vracejí podle hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnMustHaveIdentityConversion"> <source>The return expression must be of type '{0}' because this method returns by reference</source> <target state="translated">Návratový výraz musí být typu {0}, protože tato metoda vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_CloseUnimplementedInterfaceMemberWrongRefReturn"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implement '{1}' because it does not have matching return by reference.</source> <target state="translated">{0} neimplementuje člena rozhraní {1}. {2} nemůže implementovat {1}, protože nemá odpovídající návrat pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorReturnRef"> <source>The body of '{0}' cannot be an iterator block because '{0}' returns by reference</source> <target state="translated">Hlavní část objektu {0} nemůže představovat blok iterátoru, protože {0} se vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadRefReturnExpressionTree"> <source>Lambda expressions that return by reference cannot be converted to expression trees</source> <target state="translated">Výrazy lambda, které se vrací pomocí odkazu, nejde převést na stromy výrazů.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallInExpressionTree"> <source>An expression tree lambda may not contain a call to a method, property, or indexer that returns by reference</source> <target state="translated">Lambda stromu výrazů nesmí obsahovat volání do metody, vlastnosti nebo indexeru, které vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLvalueExpected"> <source>An expression cannot be used in this context because it may not be passed or returned by reference</source> <target state="translated">Výraz nelze v tomto kontextu použít, protože nesmí být předaný nebo vrácený pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnNonreturnableLocal"> <source>Cannot return '{0}' by reference because it was initialized to a value that cannot be returned by reference</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnNonreturnableLocal2"> <source>Cannot return by reference a member of '{0}' because it was initialized to a value that cannot be returned by reference</source> <target state="translated">Člen pro {0} nejde vrátit pomocí odkazu, protože bylo inicializované na hodnotu, která nemůže být vrácená pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocal"> <source>Cannot return '{0}' by reference because it is read-only</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože je to hodnota jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnRangeVariable"> <source>Cannot return the range variable '{0}' by reference</source> <target state="translated">Proměnnou rozsahu {0} nejde vrátit pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocalCause"> <source>Cannot return '{0}' by reference because it is a '{1}'</source> <target state="translated">{0} nejde vrátit pomocí odkazu, protože je to {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyLocal2Cause"> <source>Cannot return fields of '{0}' by reference because it is a '{1}'</source> <target state="translated">Pole elementu {0} nejde vrátit pomocí odkazu, protože je to {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonly"> <source>A readonly field cannot be returned by writable reference</source> <target state="translated">Pole jen pro čtení nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyStatic"> <source>A static readonly field cannot be returned by writable reference</source> <target state="translated">Statické pole jen pro čtení nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonly2"> <source>Members of readonly field '{0}' cannot be returned by writable reference</source> <target state="translated">Členy pole jen pro čtení {0} nejde vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnReadonlyStatic2"> <source>Fields of static readonly field '{0}' cannot be returned by writable reference</source> <target state="translated">Pole statického pole jen pro čtení {0} nejdou vrátit zapisovatelným odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnParameter"> <source>Cannot return a parameter by reference '{0}' because it is not a ref or out parameter</source> <target state="translated">Parametr nejde vrátit pomocí odkazu {0}, protože nejde o parametr Ref nebo Out.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnParameter2"> <source>Cannot return by reference a member of parameter '{0}' because it is not a ref or out parameter</source> <target state="translated">Člen parametru {0} nejde vrátit pomocí odkazu, protože nejde o parametr ref nebo out.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLocal"> <source>Cannot return local '{0}' by reference because it is not a ref local</source> <target state="translated">Lokální proměnnou {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnLocal2"> <source>Cannot return a member of local '{0}' by reference because it is not a ref local</source> <target state="translated">Člen lokální proměnné {0} nejde vrátit pomocí odkazu, protože nejde o lokální proměnnou podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturnStructThis"> <source>Struct members cannot return 'this' or other instance members by reference</source> <target state="translated">Členy struktury nemůžou vracet this nebo jiné členy instance pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeOther"> <source>Expression cannot be used in this context because it may indirectly expose variables outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde výraz použít, protože může nepřímo vystavit proměnné mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeLocal"> <source>Cannot use local '{0}' in this context because it may expose referenced variables outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít místní {0}, protože může vystavit odkazované proměnné mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeCall"> <source>Cannot use a result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít výsledek z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeCall2"> <source>Cannot use a member of result of '{0}' in this context because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">V tomto kontextu nejde použít člena výsledku z {0}, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_CallArgMixing"> <source>This combination of arguments to '{0}' is disallowed because it may expose variables referenced by parameter '{1}' outside of their declaration scope</source> <target state="translated">Tato kombinace argumentů pro {0} je zakázaná, protože může vystavit proměnné, na které odkazuje parametr {1}, mimo jejich rozsah deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_MismatchedRefEscapeInTernary"> <source>Branches of a ref conditional operator cannot refer to variables with incompatible declaration scopes</source> <target state="translated">Větve podmíněného operátoru REF nemůžou odkazovat na proměnné s nekompatibilními obory deklarace.</target> <note /> </trans-unit> <trans-unit id="ERR_EscapeStackAlloc"> <source>A result of a stackalloc expression of type '{0}' cannot be used in this context because it may be exposed outside of the containing method</source> <target state="translated">Výsledek výrazu stackalloc typu {0} nejde v tomto kontextu použít, protože může být vystavený mimo obsahující metodu.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializeByValueVariableWithReference"> <source>Cannot initialize a by-value variable with a reference</source> <target state="translated">Proměnnou podle hodnoty nejde inicializovat odkazem.</target> <note /> </trans-unit> <trans-unit id="ERR_InitializeByReferenceVariableWithValue"> <source>Cannot initialize a by-reference variable with a value</source> <target state="translated">Proměnnou podle odkazu nejde inicializovat hodnotou.</target> <note /> </trans-unit> <trans-unit id="ERR_RefAssignmentMustHaveIdentityConversion"> <source>The expression must be of type '{0}' because it is being assigned by reference</source> <target state="translated">Výraz musí být typu {0}, protože se přiřazuje pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_ByReferenceVariableMustBeInitialized"> <source>A declaration of a by-reference variable must have an initializer</source> <target state="translated">Deklarace proměnné podle odkazu musí mít inicializátor.</target> <note /> </trans-unit> <trans-unit id="ERR_AnonDelegateCantUseLocal"> <source>Cannot use ref local '{0}' inside an anonymous method, lambda expression, or query expression</source> <target state="translated">Místní hodnotu odkazu {0} nejde použít uvnitř anonymní metody, výrazu lambda nebo výrazu dotazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadIteratorLocalType"> <source>Iterators cannot have by-reference locals</source> <target state="translated">Iterátory nemůžou mít lokální proměnné podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncLocalType"> <source>Async methods cannot have by-reference locals</source> <target state="translated">Asynchronní metody nemůžou mít lokální proměnné podle odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefReturningCallAndAwait"> <source>'await' cannot be used in an expression containing a call to '{0}' because it returns by reference</source> <target state="translated">'Argument await nejde použít ve výrazu obsahujícím volání do {0}, protože se vrací pomocí odkazu.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalAndAwait"> <source>'await' cannot be used in an expression containing a ref conditional operator</source> <target state="translated">'Await nejde použít ve výrazu, který obsahuje podmíněný operátor REF.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalNeedsTwoRefs"> <source>Both conditional operator values must be ref values or neither may be a ref value</source> <target state="translated">Obě hodnoty podmíněného operátoru musí být hodnoty ref nebo ani jedna z nich nesmí být hodnota ref.</target> <note /> </trans-unit> <trans-unit id="ERR_RefConditionalDifferentTypes"> <source>The expression must be of type '{0}' to match the alternative ref value</source> <target state="translated">Výraz musí být typu {0}, aby odpovídal alternativní hodnotě ref.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsLocalFunction"> <source>An expression tree may not contain a reference to a local function</source> <target state="translated">Strom výrazů nesmí obsahovat odkaz na místní funkci.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicLocalFunctionParamsParameter"> <source>Cannot pass argument with dynamic type to params parameter '{0}' of local function '{1}'.</source> <target state="translated">Nejde předat argument dynamického typu s parametrem params {0} místní funkce {1}.</target> <note /> </trans-unit> <trans-unit id="SyntaxTreeIsNotASubmission"> <source>Syntax tree should be created from a submission.</source> <target state="translated">Strom syntaxe by se měl vytvořit z odeslání.</target> <note /> </trans-unit> <trans-unit id="ERR_TooManyUserStrings"> <source>Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals.</source> <target state="translated">Kombinovaná délka uživatelských řetězců, které používá tento program, překročila povolený limit. Zkuste omezit použití řetězcových literálů.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternNullableType"> <source>It is not legal to use nullable type '{0}?' in a pattern; use the underlying type '{0}' instead.</source> <target state="translated">Ve vzoru se nepovoluje použití typu s možnou hodnotou null {0}?. Místo toho použijte základní typ {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PeWritingFailure"> <source>An error occurred while writing the output file: {0}.</source> <target state="translated">Při zápisu výstupního souboru došlo k chybě: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleDuplicateElementName"> <source>Tuple element names must be unique.</source> <target state="translated">Názvy elementů řazené kolekce členů musí být jedinečné.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementName"> <source>Tuple element name '{0}' is only allowed at position {1}.</source> <target state="translated">Název elementu řazené kolekce členů {0} je povolený jenom v pozici {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleReservedElementNameAnyPosition"> <source>Tuple element name '{0}' is disallowed at any position.</source> <target state="translated">Název elementu řazené kolekce členů {0} je zakázaný v jakékoliv pozici.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedTypeMemberNotFoundInAssembly"> <source>Member '{0}' was not found on type '{1}' from assembly '{2}'.</source> <target state="translated">Nenašel se člen {0} v typu {1} ze sestavení {2}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureTuples"> <source>tuples</source> <target state="translated">řazené kolekce členů</target> <note /> </trans-unit> <trans-unit id="ERR_MissingDeconstruct"> <source>No suitable 'Deconstruct' instance or extension method was found for type '{0}', with {1} out parameters and a void return type.</source> <target state="translated">Pro typ {0} s výstupními parametry ({1}) a návratovým typem void se nenašla žádná vhodná instance Deconstruct nebo rozšiřující metoda.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructRequiresExpression"> <source>Deconstruct assignment requires an expression with a type on the right-hand-side.</source> <target state="translated">Dekonstrukční přiřazení vyžaduje výraz s typem na pravé straně.</target> <note /> </trans-unit> <trans-unit id="ERR_SwitchExpressionValueExpected"> <source>The switch expression must be a value; found '{0}'.</source> <target state="translated">Výraz switch musí být hodnota. Bylo nalezeno: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternWrongType"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}'.</source> <target state="translated">Výraz typu {0} nelze zpracovat vzorem typu {1}.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning"> <source>Attribute '{0}' is ignored when public signing is specified.</source> <target state="translated">Atribut {0} se ignoruje, když je zadané veřejné podepisování.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributeIgnoredWhenPublicSigning_Title"> <source>Attribute is ignored when public signing is specified.</source> <target state="translated">Atribut se ignoruje, když je zadané veřejné podepisování.</target> <note /> </trans-unit> <trans-unit id="ERR_OptionMustBeAbsolutePath"> <source>Option '{0}' must be an absolute path.</source> <target state="translated">Možnost {0} musí být absolutní cesta.</target> <note /> </trans-unit> <trans-unit id="ERR_ConversionNotTupleCompatible"> <source>Tuple with {0} elements cannot be converted to type '{1}'.</source> <target state="translated">Řazená kolekce členů s {0} elementy se nedá převést na typ {1}.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureOutVar"> <source>out variable declaration</source> <target state="translated">deklarace externí proměnné</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList"> <source>Reference to an implicitly-typed out variable '{0}' is not permitted in the same argument list.</source> <target state="translated">Odkaz na implicitně typovanou externí proměnnou {0} není povolený ve stejném seznamu argumentů.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailedForImplicitlyTypedOutVariable"> <source>Cannot infer the type of implicitly-typed out variable '{0}'.</source> <target state="translated">Nejde odvodit typ implicitně typované externí proměnné {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable"> <source>Cannot infer the type of implicitly-typed deconstruction variable '{0}'.</source> <target state="translated">Nejde odvodit typ dekonstrukční proměnné {0} s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_DiscardTypeInferenceFailed"> <source>Cannot infer the type of implicitly-typed discard.</source> <target state="translated">Nejde odvodit typ zahození s implicitním typem.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructWrongCardinality"> <source>Cannot deconstruct a tuple of '{0}' elements into '{1}' variables.</source> <target state="translated">Řazenou kolekci členů s {0} prvky nejde dekonstruovat na proměnné {1}.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotDeconstructDynamic"> <source>Cannot deconstruct dynamic objects.</source> <target state="translated">Dynamické objekty nejde dekonstruovat.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructTooFewElements"> <source>Deconstruction must contain at least two variables.</source> <target state="translated">Dekonstrukce musí obsahovat aspoň dvě proměnné.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch"> <source>The tuple element name '{0}' is ignored because a different name or no name is specified by the target type '{1}'.</source> <target state="translated">Název elementu řazené kolekce členů {0} se ignoruje, protože cílovým typem {1} je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="WRN_TupleLiteralNameMismatch_Title"> <source>The tuple element name is ignored because a different name or no name is specified by the assignment target.</source> <target state="translated">Název elementu řazené kolekce členů se ignoruje, protože cílem přiřazení je určený jiný nebo žádný název.</target> <note /> </trans-unit> <trans-unit id="ERR_PredefinedValueTupleTypeMustBeStruct"> <source>Predefined type '{0}' must be a struct.</source> <target state="translated">Předdefinovaný typ {0} musí být struktura.</target> <note /> </trans-unit> <trans-unit id="ERR_NewWithTupleTypeSyntax"> <source>'new' cannot be used with tuple type. Use a tuple literal expression instead.</source> <target state="translated">'new není možné použít s typem řazené kolekce členů. Použijte raději literálový výraz řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_DeconstructionVarFormDisallowsSpecificType"> <source>Deconstruction 'var (...)' form disallows a specific type for 'var'.</source> <target state="translated">Forma dekonstrukce var (...) neumožňuje použít pro var konkrétní typ.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesAttributeMissing"> <source>Cannot define a class or member that utilizes tuples because the compiler required type '{0}' cannot be found. Are you missing a reference?</source> <target state="translated">Nejde definovat třídu nebo člen, který používá řazenou kolekci členů, protože se nenašel kompilátor požadovaný typem {0}. Chybí vám odkaz?</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitTupleElementNamesAttribute"> <source>Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names.</source> <target state="translated">System.Runtime.CompilerServices.TupleElementNamesAttribute nejde odkazovat explicitně. K definici názvů řazené kolekce členů použijte její syntaxi.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsOutVariable"> <source>An expression tree may not contain an out argument variable declaration.</source> <target state="translated">Strom výrazů nesmí obsahovat deklaraci proměnné argumentu out.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsDiscard"> <source>An expression tree may not contain a discard.</source> <target state="translated">Strom výrazů nesmí obsahovat zahození.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsIsMatch"> <source>An expression tree may not contain an 'is' pattern-matching operator.</source> <target state="translated">Strom výrazů nesmí obsahovat operátor odpovídající vzoru is.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleLiteral"> <source>An expression tree may not contain a tuple literal.</source> <target state="translated">Strom výrazů nesmí obsahovat literál řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsTupleConversion"> <source>An expression tree may not contain a tuple conversion.</source> <target state="translated">Strom výrazů nesmí obsahovat převod řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_SourceLinkRequiresPdb"> <source>/sourcelink switch is only supported when emitting PDB.</source> <target state="translated">Přepínač /sourcelink je podporovaný jen při vydávání PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_CannotEmbedWithoutPdb"> <source>/embed switch is only supported when emitting a PDB.</source> <target state="translated">Přepínač /embed je podporovaný jen při vydávání souboru PDB.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidInstrumentationKind"> <source>Invalid instrumentation kind: {0}</source> <target state="translated">Neplatný typ instrumentace: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_VarInvocationLvalueReserved"> <source>The syntax 'var (...)' as an lvalue is reserved.</source> <target state="translated">Syntaxe 'var (...)' jako l-hodnota je vyhrazená.</target> <note /> </trans-unit> <trans-unit id="ERR_SemiOrLBraceOrArrowExpected"> <source>{ or ; or =&gt; expected</source> <target state="translated">Očekávaly se znaky { nebo ; nebo =&gt;.</target> <note /> </trans-unit> <trans-unit id="ERR_ThrowMisplaced"> <source>A throw expression is not allowed in this context.</source> <target state="translated">Výraz throw není v tomto kontextu povolený.</target> <note /> </trans-unit> <trans-unit id="ERR_DeclarationExpressionNotPermitted"> <source>A declaration is not allowed in this context.</source> <target state="translated">Deklarace není v tomto kontextu povolená.</target> <note /> </trans-unit> <trans-unit id="ERR_MustDeclareForeachIteration"> <source>A foreach loop must declare its iteration variables.</source> <target state="translated">Smyčka foreach musí deklarovat své proměnné iterace.</target> <note /> </trans-unit> <trans-unit id="ERR_TupleElementNamesInDeconstruction"> <source>Tuple element names are not permitted on the left of a deconstruction.</source> <target state="translated">Na levé straně dekonstrukce nejsou povolené názvy prvků řazené kolekce členů.</target> <note /> </trans-unit> <trans-unit id="ERR_PossibleBadNegCast"> <source>To cast a negative value, you must enclose the value in parentheses.</source> <target state="translated">Pokud se má přetypovat záporná hodnota, musí být uzavřená v závorkách.</target> <note /> </trans-unit> <trans-unit id="ERR_ExpressionTreeContainsThrowExpression"> <source>An expression tree may not contain a throw-expression.</source> <target state="translated">Strom výrazů nesmí obsahovat výraz throw.</target> <note /> </trans-unit> <trans-unit id="ERR_BadAssemblyName"> <source>Invalid assembly name: {0}</source> <target state="translated">Neplatný název sestavení: {0}</target> <note /> </trans-unit> <trans-unit id="ERR_BadAsyncMethodBuilderTaskProperty"> <source>For type '{0}' to be used as an AsyncMethodBuilder for type '{1}', its Task property should return type '{1}' instead of type '{2}'.</source> <target state="translated">Aby se typ {0} mohl použít jako AsyncMethodBuilder pro typ {1}, měla by jeho vlastnost Task vracet typ {1} místo typu {2}.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeForwardedToMultipleAssemblies"> <source>Module '{0}' in assembly '{1}' is forwarding the type '{2}' to multiple assemblies: '{3}' and '{4}'.</source> <target state="translated">Modul {0} v sestavení {1} předává typ {2} několika sestavením: {3} a {4}.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternDynamicType"> <source>It is not legal to use the type 'dynamic' in a pattern.</source> <target state="translated">Není povoleno použít typ dynamic ve vzorku.</target> <note /> </trans-unit> <trans-unit id="ERR_BadDocumentationMode"> <source>Provided documentation mode is unsupported or invalid: '{0}'.</source> <target state="translated">Zadaný režim dokumentace je nepodporovaný nebo neplatný: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadSourceCodeKind"> <source>Provided source code kind is unsupported or invalid: '{0}'</source> <target state="translated">Zadaný druh zdrojového kódu je nepodporovaný nebo neplatný: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_BadLanguageVersion"> <source>Provided language version is unsupported or invalid: '{0}'.</source> <target state="translated">Zadaná verze jazyka je nepodporovaná nebo neplatná: {0}.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidPreprocessingSymbol"> <source>Invalid name for a preprocessing symbol; '{0}' is not a valid identifier</source> <target state="translated">Neplatný název pro symbol předzpracování; {0} není platný identifikátor.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_1"> <source>Feature '{0}' is not available in C# 7.1. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.1. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_2"> <source>Feature '{0}' is not available in C# 7.2. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.2. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersionCannotHaveLeadingZeroes"> <source>Specified language version '{0}' cannot have leading zeroes</source> <target state="translated">Zadaná verze jazyka {0} nemůže obsahovat úvodní nuly.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidAssignment"> <source>A value of type 'void' may not be assigned.</source> <target state="translated">Hodnota typu void se nesmí přiřazovat.</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental"> <source>'{0}' is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">{0} slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změně nebo odebrání.</target> <note /> </trans-unit> <trans-unit id="WRN_Experimental_Title"> <source>Type is for evaluation purposes only and is subject to change or removal in future updates.</source> <target state="translated">Typ slouží jen pro účely vyhodnocení a v budoucích aktualizacích může dojít ke změnám nebo odebrání.</target> <note /> </trans-unit> <trans-unit id="ERR_CompilerAndLanguageVersion"> <source>Compiler version: '{0}'. Language version: {1}.</source> <target state="translated">Verze kompilátoru: {0}. Jazyková verze: {1}</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncMain"> <source>async main</source> <target state="translated">Asynchronní funkce main</target> <note /> </trans-unit> <trans-unit id="ERR_TupleInferredNamesNotAvailable"> <source>Tuple element name '{0}' is inferred. Please use language version {1} or greater to access an element by its inferred name.</source> <target state="translated">Název elementu řazené kolekce členů {0} je odvozený. Pokud k elementu chcete získat přístup pomocí jeho odvozeného názvu, použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="ERR_VoidInTuple"> <source>A tuple may not contain a value of type 'void'.</source> <target state="translated">Řazená kolekce členů nemůže obsahovat hodnotu typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_NonTaskMainCantBeAsync"> <source>A void or int returning entry point cannot be async</source> <target state="translated">Vstupní bod, který vrací void nebo int, nemůže být asynchronní.</target> <note /> </trans-unit> <trans-unit id="ERR_PatternWrongGenericTypeInVersion"> <source>An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater.</source> <target state="translated">V C# {2} nelze výraz typu {0} zpracovat vzorem typu {1}. Použijte prosím jazyk verze {3} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLocalFunction"> <source>The local function '{0}' is declared but never used</source> <target state="translated">Lokální funkce {0} je deklarovaná, ale vůbec se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="WRN_UnreferencedLocalFunction_Title"> <source>Local function is declared but never used</source> <target state="translated">Lokální funkce je deklarovaná, ale vůbec se nepoužívá.</target> <note /> </trans-unit> <trans-unit id="ERR_LocalFunctionMissingBody"> <source>Local function '{0}' must declare a body because it is not marked 'static extern'.</source> <target state="translated">Místní funkce {0} musí deklarovat tělo, protože není označená jako static extern.</target> <note /> </trans-unit> <trans-unit id="ERR_InvalidDebugInfo"> <source>Unable to read debug information of method '{0}' (token 0x{1:X8}) from assembly '{2}'</source> <target state="translated">Informace o ladění metody {0} (token 0x{1:X8}) ze sestavení {2} nelze přečíst.</target> <note /> </trans-unit> <trans-unit id="IConversionExpressionIsNotCSharpConversion"> <source>{0} is not a valid C# conversion expression</source> <target state="translated">Výraz {0} není platným výrazem převodu C#.</target> <note /> </trans-unit> <trans-unit id="ERR_DynamicLocalFunctionTypeParameter"> <source>Cannot pass argument with dynamic type to generic local function '{0}' with inferred type arguments.</source> <target state="translated">Obecné lokální funkci {0} s odvozenými argumenty typu nelze předat argument s dynamickým typem.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureLeadingDigitSeparator"> <source>leading digit separator</source> <target state="translated">oddělovač úvodní číslice</target> <note /> </trans-unit> <trans-unit id="ERR_ExplicitReservedAttr"> <source>Do not use '{0}'. This is reserved for compiler usage.</source> <target state="translated">Nepoužívejte {0}. Je vyhrazený pro použití v kompilátoru.</target> <note /> </trans-unit> <trans-unit id="ERR_TypeReserved"> <source>The type name '{0}' is reserved to be used by the compiler.</source> <target state="translated">Název typu {0} je vyhrazený pro použití kompilátorem.</target> <note /> </trans-unit> <trans-unit id="ERR_InExtensionMustBeValueType"> <source>The first parameter of the 'in' extension method '{0}' must be a concrete (non-generic) value type.</source> <target state="translated">Prvním parametrem metody rozšíření in {0} musí být konkrétní (neobecný) typ hodnoty.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldsInRoStruct"> <source>Instance fields of readonly structs must be readonly.</source> <target state="translated">Pole instancí struktur jen pro čtení musí být jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_AutoPropsInRoStruct"> <source>Auto-implemented instance properties in readonly structs must be readonly.</source> <target state="translated">Vlastnosti automaticky implementované instance ve strukturách jen pro čtení musí být jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="ERR_FieldlikeEventsInRoStruct"> <source>Field-like events are not allowed in readonly structs.</source> <target state="translated">Události podobné poli nejsou povolené ve strukturách jen pro čtení.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureRefExtensionMethods"> <source>ref extension methods</source> <target state="translated">rozšiřující metody REF</target> <note /> </trans-unit> <trans-unit id="ERR_StackAllocConversionNotPossible"> <source>Conversion of a stackalloc expression of type '{0}' to type '{1}' is not possible.</source> <target state="translated">Převod výrazu stackalloc typu {0} na typ {1} není možný.</target> <note /> </trans-unit> <trans-unit id="ERR_RefExtensionMustBeValueTypeOrConstrainedToOne"> <source>The first parameter of a 'ref' extension method '{0}' must be a value type or a generic type constrained to struct.</source> <target state="translated">První parametr rozšiřující metody ref {0} musí být typem hodnoty nebo obecným typem omezeným na strukturu.</target> <note /> </trans-unit> <trans-unit id="ERR_OutAttrOnInParam"> <source>An in parameter cannot have the Out attribute.</source> <target state="translated">Parametr in nemůže obsahovat atribut Out.</target> <note /> </trans-unit> <trans-unit id="ICompoundAssignmentOperationIsNotCSharpCompoundAssignment"> <source>{0} is not a valid C# compound assignment operation</source> <target state="translated">{0} není platná operace složeného přiřazení jazyka C#.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalse"> <source>Filter expression is a constant 'false', consider removing the catch clause</source> <target state="translated">Výraz filtru je konstantní hodnota false. Zvažte odebrání klauzule catch.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalse_Title"> <source>Filter expression is a constant 'false'</source> <target state="translated">Výraz filtru je konstantní hodnota false.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalseRedundantTryCatch"> <source>Filter expression is a constant 'false', consider removing the try-catch block</source> <target state="translated">Výraz filtru je konstantní hodnota false. Zvažte odebrání bloku try-catch.</target> <note /> </trans-unit> <trans-unit id="WRN_FilterIsConstantFalseRedundantTryCatch_Title"> <source>Filter expression is a constant 'false'. </source> <target state="translated">Výraz filtru je konstantní hodnota false. </target> <note /> </trans-unit> <trans-unit id="ERR_CantUseVoidInArglist"> <source>__arglist cannot have an argument of void type</source> <target state="translated">__arglist nemůže mít argument typu void.</target> <note /> </trans-unit> <trans-unit id="ERR_ConditionalInInterpolation"> <source>A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression.</source> <target state="translated">Podmíněný výraz se nedá použít přímo v interpolaci řetězce, protože na konci interpolace je dvojtečka. Dejte podmíněný výraz do závorek.</target> <note /> </trans-unit> <trans-unit id="ERR_DoNotUseFixedBufferAttrOnProperty"> <source>Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute on a property</source> <target state="translated">Nepoužívejte u vlastnosti atribut System.Runtime.CompilerServices.FixedBuffer.</target> <note /> </trans-unit> <trans-unit id="ERR_FeatureNotAvailableInVersion7_3"> <source>Feature '{0}' is not available in C# 7.3. Please use language version {1} or greater.</source> <target state="translated">Funkce {0} není dostupná v jazyce C# 7.3. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributesOnBackingFieldsNotAvailable"> <source>Field-targeted attributes on auto-properties are not supported in language version {0}. Please use language version {1} or greater.</source> <target state="translated">Atributy cílící na pole se u automatických vlastností v jazyku verze {0} nepodporují. Použijte prosím jazyk verze {1} nebo vyšší.</target> <note /> </trans-unit> <trans-unit id="WRN_AttributesOnBackingFieldsNotAvailable_Title"> <source>Field-targeted attributes on auto-properties are not supported in this version of the language.</source> <target state="translated">Atributy cílící na pole se u automatických vlastností v této verzi jazyka nepodporují.</target> <note /> </trans-unit> <trans-unit id="IDS_FeatureAsyncStreams"> <source>async streams</source> <target state="translated">asynchronní streamy</target> <note /> </trans-unit> <trans-unit id="ERR_NoConvToIAsyncDisp"> <source>'{0}': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.</source> <target state="translated">{0}: typ použitý v asynchronním příkazu using musí být implicitně převoditelný na System.IAsyncDisposable nebo musí implementovat odpovídající metodu DisposeAsync.</target> <note /> </trans-unit> <trans-unit id="ERR_BadGetAsyncEnumerator"> <source>Asynchronous foreach requires that the return type '{0}' of '{1}' must have a suitable public 'MoveNextAsync' method and public 'Current' property</source> <target state="translated">Asynchronní příkaz foreach vyžaduje, aby návratový typ {0} pro {1} měl vhodnou veřejnou metodu MoveNextAsync a veřejnou vlastnost Current.</target> <note /> </trans-unit> <trans-unit id="ERR_MultipleIAsyncEnumOfT"> <source>Asynchronous foreach statement cannot operate on variables of type '{0}' because it implements multiple instantiations of '{1}'; try casting to a specific interface instantiation</source> <target state="translated">Asynchronní příkaz foreach nejde použít pro proměnné typu {0}, protože implementuje vytváření víc instancí {1}. Zkuste přetypování na konkrétní instanci rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_InterfacesCantContainConversionOrEqualityOperators"> <source>Conversion, equality, or inequality operators declared in interfaces must be abstract</source> <target state="needs-review-translation">Rozhraní nemůžou obsahovat operátory převodu, rovnosti nebo nerovnosti.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation"> <source>Target runtime doesn't support default interface implementation.</source> <target state="translated">Cílový modul runtime nepodporuje implementaci výchozího rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because the target runtime doesn't support default interface implementation.</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože cílový modul runtime nepodporuje implementaci výchozího rozhraní.</target> <note /> </trans-unit> <trans-unit id="ERR_ImplicitImplementationOfNonPublicInterfaceMember"> <source>'{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement a non-public member in C# {3}. Please use language version '{4}' or greater.</source> <target state="new">'{0}' does not implement interface member '{1}'. '{2}' cannot implicitly implement a non-public member in C# {3}. Please use language version '{4}' or greater.</target> <note /> </trans-unit> <trans-unit id="ERR_MostSpecificImplementationIsNotFound"> <source>Interface member '{0}' does not have a most specific implementation. Neither '{1}', nor '{2}' are most specific.</source> <target state="translated">Člen rozhraní {0} nemá nejvíce specifickou implementaci. {1} ani {2} nejsou nejvíce specifické.</target> <note /> </trans-unit> <trans-unit id="ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember"> <source>'{0}' cannot implement interface member '{1}' in type '{2}' because feature '{3}' is not available in C# {4}. Please use language version '{5}' or greater.</source> <target state="translated">{0} nemůže implementovat člen rozhraní {1} v typu {2}, protože funkce {3} není v jazyce C# {4} k dispozici. Použijte prosím verzi jazyka {5} nebo vyšší.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/VisualBasic/Portable/ImplementAbstractClass/VisualBasicImplementAbstractClassCodeFixProvider.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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.ImplementAbstractClass Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ImplementAbstractClass), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateType)> Friend Class VisualBasicImplementAbstractClassCodeFixProvider Inherits AbstractImplementAbstractClassCodeFixProvider(Of ClassBlockSyntax) Friend Const BC30610 As String = "BC30610" ' Class 'goo' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() MyBase.New(BC30610) End Sub Protected Overrides Function GetClassIdentifier(classNode As ClassBlockSyntax) As SyntaxToken Return classNode.ClassStatement.Identifier 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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.ImplementAbstractClass Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ImplementAbstractClass), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateType)> Friend Class VisualBasicImplementAbstractClassCodeFixProvider Inherits AbstractImplementAbstractClassCodeFixProvider(Of ClassBlockSyntax) Friend Const BC30610 As String = "BC30610" ' Class 'goo' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() MyBase.New(BC30610) End Sub Protected Overrides Function GetClassIdentifier(classNode As ClassBlockSyntax) As SyntaxToken Return classNode.ClassStatement.Identifier End Function End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./docs/wiki/Getting-Started-on-Visual-Studio-2015-Preview.md
1. Set up a box with Visual Studio 2015 Preview. Either [install Visual Studio 2015 Preview](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 Preview SDK](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](http://visualstudiogallery.msdn.microsoft.com/849f3ab1-05cf-4682-b4af-ef995e2aa1a5) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](http://visualstudiogallery.msdn.microsoft.com/70e184da-9b3a-402f-b210-d62a898e2887) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
1. Set up a box with Visual Studio 2015 Preview. Either [install Visual Studio 2015 Preview](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs), or grab a [prebuilt Azure VM image](http://blogs.msdn.com/b/visualstudioalm/archive/2014/06/04/visual-studio-14-ctp-now-available-in-the-virtual-machine-azure-gallery.aspx). 2. Install the [Visual Studio 2015 Preview SDK](http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs). You'll need to do this even if you're using the Azure VM image. 3. Install the [SDK Templates VSIX package](http://visualstudiogallery.msdn.microsoft.com/849f3ab1-05cf-4682-b4af-ef995e2aa1a5) to get the Visual Studio project templates. 4. Install the [Syntax Visualizer VSIX package](http://visualstudiogallery.msdn.microsoft.com/70e184da-9b3a-402f-b210-d62a898e2887) to get a [Syntax Visualizer tool window](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Syntax-Visualizer.md) to help explore the syntax trees you'll be analyzing.
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.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.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.Implementation.Preview Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Public Class PreviewTests Inherits AbstractVisualBasicCodeActionTest Private Const s_addedDocumentName As String = "AddedDocument" Private Const s_addedDocumentText As String = "Class C1 : End Class" Private Shared s_removedMetadataReferenceDisplayName As String = "" Private Const s_addedProjectName As String = "AddedProject" Private Shared ReadOnly s_addedProjectId As ProjectId = ProjectId.CreateNewId() Private Const s_changedDocumentText As String = "Class C : End Class" Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New MyCodeRefactoringProvider() End Function Private Class MyCodeRefactoringProvider : Inherits CodeRefactoringProvider Public NotOverridable Overrides Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task Dim codeAction = New MyCodeAction(context.Document) context.RegisterRefactoring(codeAction, context.Span) Return Task.CompletedTask End Function Private Class MyCodeAction : Inherits CodeAction Private ReadOnly _oldDocument As Document Public Sub New(oldDocument As Document) Me._oldDocument = oldDocument End Sub Public Overrides ReadOnly Property Title As String Get Return "Title" End Get End Property Protected Overrides Function GetChangedSolutionAsync(cancellationToken As CancellationToken) As Task(Of Solution) Dim solution = _oldDocument.Project.Solution ' Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, s_addedDocumentName), s_addedDocumentName, s_addedDocumentText) ' Remove a reference - This will result in a string preview. Dim removedReference = _oldDocument.Project.MetadataReferences.Last() s_removedMetadataReferenceDisplayName = removedReference.Display solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference) ' Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), s_addedProjectName, s_addedProjectName, LanguageNames.CSharp)) ' Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, VisualBasicSyntaxTree.ParseText(s_changedDocumentText).GetRoot()) Return Task.FromResult(solution) End Function End Class End Class Private Async Function GetMainDocumentAndPreviewsAsync( parameters As TestParameters, workspace As TestWorkspace) As Task(Of (document As Document, previews As SolutionPreviewResult)) Dim document = GetDocument(workspace) Dim provider = CreateCodeRefactoringProvider(workspace, parameters) Dim span = document.GetSyntaxRootAsync().Result.Span Dim refactorings = New List(Of CodeAction)() Dim context = New CodeRefactoringContext(document, span, Sub(a) refactorings.Add(a), CancellationToken.None) provider.ComputeRefactoringsAsync(context).Wait() Dim action = refactorings.Single() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)() Dim previews = Await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None) Return (document, previews) End Function <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/14421")> Public Async Function TestPickTheRightPreview_NoPreference() As Task Dim parameters As New TestParameters() Using workspace = CreateWorkspaceFromOptions("Class D : End Class", parameters) Dim tuple = Await GetMainDocumentAndPreviewsAsync(parameters, workspace) Dim document = tuple.document Dim previews = tuple.previews ' The changed document comes first. Dim previewObjects = Await previews.GetPreviewsAsync() Dim preview = previewObjects(0) Assert.NotNull(preview) Assert.True(TypeOf preview Is DifferenceViewerPreview) Dim diffView = DirectCast(preview, DifferenceViewerPreview) Dim text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString() Assert.Equal(s_changedDocumentText, text) diffView.Dispose() ' Then comes the removed metadata reference. preview = previewObjects(1) Assert.NotNull(preview) Assert.True(TypeOf preview Is String) text = DirectCast(preview, String) Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal) ' And finally the added project. preview = previewObjects(2) Assert.NotNull(preview) Assert.True(TypeOf preview Is String) text = DirectCast(preview, String) Assert.Contains(s_addedProjectName, text, StringComparison.Ordinal) End Using 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.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.Implementation.Preview Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Public Class PreviewTests Inherits AbstractVisualBasicCodeActionTest Private Const s_addedDocumentName As String = "AddedDocument" Private Const s_addedDocumentText As String = "Class C1 : End Class" Private Shared s_removedMetadataReferenceDisplayName As String = "" Private Const s_addedProjectName As String = "AddedProject" Private Shared ReadOnly s_addedProjectId As ProjectId = ProjectId.CreateNewId() Private Const s_changedDocumentText As String = "Class C : End Class" Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New MyCodeRefactoringProvider() End Function Private Class MyCodeRefactoringProvider : Inherits CodeRefactoringProvider Public NotOverridable Overrides Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task Dim codeAction = New MyCodeAction(context.Document) context.RegisterRefactoring(codeAction, context.Span) Return Task.CompletedTask End Function Private Class MyCodeAction : Inherits CodeAction Private ReadOnly _oldDocument As Document Public Sub New(oldDocument As Document) Me._oldDocument = oldDocument End Sub Public Overrides ReadOnly Property Title As String Get Return "Title" End Get End Property Protected Overrides Function GetChangedSolutionAsync(cancellationToken As CancellationToken) As Task(Of Solution) Dim solution = _oldDocument.Project.Solution ' Add a document - This will result in IWpfTextView previews. solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, s_addedDocumentName), s_addedDocumentName, s_addedDocumentText) ' Remove a reference - This will result in a string preview. Dim removedReference = _oldDocument.Project.MetadataReferences.Last() s_removedMetadataReferenceDisplayName = removedReference.Display solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference) ' Add a project - This will result in a string preview. solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), s_addedProjectName, s_addedProjectName, LanguageNames.CSharp)) ' Change a document - This will result in IWpfTextView previews. solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, VisualBasicSyntaxTree.ParseText(s_changedDocumentText).GetRoot()) Return Task.FromResult(solution) End Function End Class End Class Private Async Function GetMainDocumentAndPreviewsAsync( parameters As TestParameters, workspace As TestWorkspace) As Task(Of (document As Document, previews As SolutionPreviewResult)) Dim document = GetDocument(workspace) Dim provider = CreateCodeRefactoringProvider(workspace, parameters) Dim span = document.GetSyntaxRootAsync().Result.Span Dim refactorings = New List(Of CodeAction)() Dim context = New CodeRefactoringContext(document, span, Sub(a) refactorings.Add(a), CancellationToken.None) provider.ComputeRefactoringsAsync(context).Wait() Dim action = refactorings.Single() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)() Dim previews = Await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None) Return (document, previews) End Function <WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/14421")> Public Async Function TestPickTheRightPreview_NoPreference() As Task Dim parameters As New TestParameters() Using workspace = CreateWorkspaceFromOptions("Class D : End Class", parameters) Dim tuple = Await GetMainDocumentAndPreviewsAsync(parameters, workspace) Dim document = tuple.document Dim previews = tuple.previews ' The changed document comes first. Dim previewObjects = Await previews.GetPreviewsAsync() Dim preview = previewObjects(0) Assert.NotNull(preview) Assert.True(TypeOf preview Is DifferenceViewerPreview) Dim diffView = DirectCast(preview, DifferenceViewerPreview) Dim text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString() Assert.Equal(s_changedDocumentText, text) diffView.Dispose() ' Then comes the removed metadata reference. preview = previewObjects(1) Assert.NotNull(preview) Assert.True(TypeOf preview Is String) text = DirectCast(preview, String) Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal) ' And finally the added project. preview = previewObjects(2) Assert.NotNull(preview) Assert.True(TypeOf preview Is String) text = DirectCast(preview, String) Assert.Contains(s_addedProjectName, text, StringComparison.Ordinal) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/AggregateKeywordRecommender.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.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the Aggregate operator. ''' </summary> Friend Class AggregateKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Aggregate", VBFeaturesResources.Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsAnyExpressionContext OrElse context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) 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.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries ''' <summary> ''' Recommends the Aggregate operator. ''' </summary> Friend Class AggregateKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("Aggregate", VBFeaturesResources.Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Return If(context.IsAnyExpressionContext OrElse context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty) End Function End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Test/Resources/Core/SymbolsTests/CyclicInheritance/Class1.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. ' vbc /target:library class1.vb Public Class C1 Inherits C2 End Class Public Interface I0 End Interface Public Interface I1 Inherits I2 End Interface
' 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. ' vbc /target:library class1.vb Public Class C1 Inherits C2 End Class Public Interface I0 End Interface Public Interface I1 Inherits I2 End Interface
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/CSharpTest2/Recommendations/NotnullKeywordRecommenderTests.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class NotNullKeywordRecommenderTests : RecommenderTests { private readonly NotNullKeywordRecommender _recommender = new NotNullKeywordRecommender(); public NotNullKeywordRecommenderTests() { this.keywordText = "notnull"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [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 TestNotAfterName_Type() { await VerifyAbsenceAsync( @"class Test $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Type() { await VerifyAbsenceAsync( @"class Test<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Type() { await VerifyAbsenceAsync( @"class Test<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Type() { await VerifyKeywordAsync( @"class Test<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Type() { await VerifyAbsenceAsync( @"class Test<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Type() { await VerifyKeywordAsync( @"class Test<T> where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_Method() { await VerifyAbsenceAsync( @"class Test { void M $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Method() { await VerifyKeywordAsync( @"class Test { void M<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Method() { await VerifyKeywordAsync( @"class Test { void M<T> where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_Delegate() { await VerifyAbsenceAsync( @"delegate void D $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Delegate() { await VerifyKeywordAsync( @"delegate void D<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Delegate() { await VerifyKeywordAsync( @"delegate void D<T>() where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_LocalFunction() { await VerifyKeywordAsync( @"class Test { void N() { void M<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_LocalFunction() { await VerifyKeywordAsync( @"class Test { void N() { void M<T> where T : I, $$"); } } }
// 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class NotNullKeywordRecommenderTests : RecommenderTests { private readonly NotNullKeywordRecommender _recommender = new NotNullKeywordRecommender(); public NotNullKeywordRecommenderTests() { this.keywordText = "notnull"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [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 TestNotAfterName_Type() { await VerifyAbsenceAsync( @"class Test $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Type() { await VerifyAbsenceAsync( @"class Test<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Type() { await VerifyAbsenceAsync( @"class Test<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Type() { await VerifyKeywordAsync( @"class Test<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Type() { await VerifyAbsenceAsync( @"class Test<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Type() { await VerifyKeywordAsync( @"class Test<T> where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_Method() { await VerifyAbsenceAsync( @"class Test { void M $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Method() { await VerifyKeywordAsync( @"class Test { void M<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Method() { await VerifyAbsenceAsync( @"class Test { void M<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Method() { await VerifyKeywordAsync( @"class Test { void M<T> where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_Delegate() { await VerifyAbsenceAsync( @"delegate void D $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_Delegate() { await VerifyKeywordAsync( @"delegate void D<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_Delegate() { await VerifyAbsenceAsync( @"delegate void D<T>() where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_Delegate() { await VerifyKeywordAsync( @"delegate void D<T>() where T : I, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterName_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClause_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterWhereClauseType_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where T $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterWhereClauseColon_LocalFunction() { await VerifyKeywordAsync( @"class Test { void N() { void M<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeConstraint_LocalFunction() { await VerifyAbsenceAsync( @"class Test { void N() { void M<T> where T : I $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeConstraintComma_LocalFunction() { await VerifyKeywordAsync( @"class Test { void N() { void M<T> where T : I, $$"); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/MyBaseMyClassSemanticsTests.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.CompilerServices Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class MyBaseMyClassSemanticsTests : Inherits BasicTestBase <Fact> Public Sub MeMyBaseMyClassSymbolsTest() Dim compilationDef = <compilation name="MeMyBaseMyClassSymbolsTest"> <file name="a.vb"> Imports System Module M1 Class B1 Protected Overridable Function F() As String Return "B1::F" End Function End Class Class B2 Inherits B1 Protected Overrides Function F() As String Return "B2::F" End Function Public Sub TestMe() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#0 Me 0#].F, Func(Of String))() Console.WriteLine(f1()) End Sub Public Sub TestMyClass() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#1 MyClass 1#].F, Func(Of String))() Console.WriteLine(f1()) End Sub Public Sub TestMyBase() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#2 MyBase 2#].F, Func(Of String))() Console.WriteLine(f1()) End Sub End Class End Module </file> </compilation> Dim tree As SyntaxTree = Nothing Dim nodes As New List(Of SyntaxNode) Dim compilation = Compile(compilationDef, tree, nodes) Assert.Equal(3, nodes.Count) Dim model = compilation.GetSemanticModel(tree) Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax)) Assert.Equal(info0.Type.Name, "B2") Dim info1 = model.GetSemanticInfoSummary(DirectCast(nodes(1), ExpressionSyntax)) Assert.Equal(info1.Type.Name, "B2") Dim info2 = model.GetSemanticInfoSummary(DirectCast(nodes(2), ExpressionSyntax)) Assert.Equal(info2.Type.Name, "B1") End Sub #Region "Utils" Private Sub CheckFieldNameAndLocation(type As TypeSymbol, tree As SyntaxTree, identifierIndex As Integer, fieldName As String, Optional isKey As Boolean = False) Dim node = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, identifierIndex).AsNode, IdentifierNameSyntax) Dim span As TextSpan = node.Span Assert.Equal(fieldName, node.ToString()) Dim anonymousType = DirectCast(type, NamedTypeSymbol) Dim [property] As PropertySymbol = anonymousType.GetMember(Of PropertySymbol)(fieldName) Assert.NotNull([property]) Assert.Equal(fieldName, [property].Name) Assert.Equal(1, [property].Locations.Length) Assert.Equal(span, [property].Locations(0).SourceSpan) Dim getter As MethodSymbol = [property].GetMethod Assert.NotNull(getter) Assert.Equal("get_" & fieldName, getter.Name) If Not isKey Then Dim setter As MethodSymbol = [property].SetMethod Assert.NotNull(setter) Assert.Equal("set_" & fieldName, setter.Name) Else Assert.True([property].IsReadOnly) End If ' Do we actually need this?? 'Dim field As FieldSymbol = anonymousType.GetMember(Of FieldSymbol)("$" & fieldName) 'Assert.NotNull(field) 'Assert.Equal("$" & fieldName, field.Name) 'Assert.Equal(isKey, field.IsReadOnly) End Sub Private Function Compile(text As XElement, ByRef tree As SyntaxTree, nodes As List(Of SyntaxNode), Optional errors As XElement = Nothing) As VisualBasicCompilation Dim spans As New List(Of TextSpan) ExtractTextIntervals(text, spans) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(text, {SystemRef, SystemCoreRef, MsvbRef}) If errors Is Nothing Then CompilationUtils.AssertNoErrors(compilation) Else CompilationUtils.AssertTheseDiagnostics(compilation, errors) End If tree = compilation.SyntaxTrees(0) For Each span In spans Dim stack As New Stack(Of SyntaxNode) stack.Push(tree.GetRoot()) While stack.Count > 0 Dim node = stack.Pop() If span.Contains(node.Span) Then nodes.Add(node) Exit While End If For Each child In node.ChildNodes stack.Push(child) Next End While Next Return compilation End Function Private Shared Sub ExtractTextIntervals(text As XElement, nodes As List(Of TextSpan)) text.<file>.Value = text.<file>.Value.Trim().Replace(vbLf, vbCrLf) Dim index As Integer = 0 Do Dim startMarker = "[#" & index Dim endMarker = index & "#]" ' opening '[#{0-9}' Dim start = text.<file>.Value.IndexOf(startMarker, StringComparison.Ordinal) If start < 0 Then Exit Do End If ' closing '{0-9}#]' Dim [end] = text.<file>.Value.IndexOf(endMarker, StringComparison.Ordinal) Assert.InRange([end], 0, Int32.MaxValue) nodes.Add(New TextSpan(start, [end] - start + 3)) text.<file>.Value = text.<file>.Value.Replace(startMarker, " ").Replace(endMarker, " ") index += 1 Assert.InRange(index, 0, 9) Loop End Sub Private Shared Function GetNamedTypeSymbol(c As VisualBasicCompilation, namedTypeName As String, Optional fromCorLib As Boolean = False) As NamedTypeSymbol Dim nameParts = namedTypeName.Split("."c) Dim srcAssembly = DirectCast(c.Assembly, SourceAssemblySymbol) Dim nsSymbol As NamespaceSymbol = (If(fromCorLib, srcAssembly.CorLibrary, srcAssembly)).GlobalNamespace For Each ns In nameParts.Take(nameParts.Length - 1) nsSymbol = DirectCast(nsSymbol.GetMember(ns), NamespaceSymbol) Next Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol) End Function #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.Runtime.CompilerServices Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.ExtensionMethods Public Class MyBaseMyClassSemanticsTests : Inherits BasicTestBase <Fact> Public Sub MeMyBaseMyClassSymbolsTest() Dim compilationDef = <compilation name="MeMyBaseMyClassSymbolsTest"> <file name="a.vb"> Imports System Module M1 Class B1 Protected Overridable Function F() As String Return "B1::F" End Function End Class Class B2 Inherits B1 Protected Overrides Function F() As String Return "B2::F" End Function Public Sub TestMe() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#0 Me 0#].F, Func(Of String))() Console.WriteLine(f1()) End Sub Public Sub TestMyClass() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#1 MyClass 1#].F, Func(Of String))() Console.WriteLine(f1()) End Sub Public Sub TestMyBase() Dim prefix = "->" Dim f1 As Func(Of String) = Function() prefix &amp; DirectCast(AddressOf [#2 MyBase 2#].F, Func(Of String))() Console.WriteLine(f1()) End Sub End Class End Module </file> </compilation> Dim tree As SyntaxTree = Nothing Dim nodes As New List(Of SyntaxNode) Dim compilation = Compile(compilationDef, tree, nodes) Assert.Equal(3, nodes.Count) Dim model = compilation.GetSemanticModel(tree) Dim info0 = model.GetSemanticInfoSummary(DirectCast(nodes(0), ExpressionSyntax)) Assert.Equal(info0.Type.Name, "B2") Dim info1 = model.GetSemanticInfoSummary(DirectCast(nodes(1), ExpressionSyntax)) Assert.Equal(info1.Type.Name, "B2") Dim info2 = model.GetSemanticInfoSummary(DirectCast(nodes(2), ExpressionSyntax)) Assert.Equal(info2.Type.Name, "B1") End Sub #Region "Utils" Private Sub CheckFieldNameAndLocation(type As TypeSymbol, tree As SyntaxTree, identifierIndex As Integer, fieldName As String, Optional isKey As Boolean = False) Dim node = DirectCast(tree.FindNodeOrTokenByKind(SyntaxKind.IdentifierName, identifierIndex).AsNode, IdentifierNameSyntax) Dim span As TextSpan = node.Span Assert.Equal(fieldName, node.ToString()) Dim anonymousType = DirectCast(type, NamedTypeSymbol) Dim [property] As PropertySymbol = anonymousType.GetMember(Of PropertySymbol)(fieldName) Assert.NotNull([property]) Assert.Equal(fieldName, [property].Name) Assert.Equal(1, [property].Locations.Length) Assert.Equal(span, [property].Locations(0).SourceSpan) Dim getter As MethodSymbol = [property].GetMethod Assert.NotNull(getter) Assert.Equal("get_" & fieldName, getter.Name) If Not isKey Then Dim setter As MethodSymbol = [property].SetMethod Assert.NotNull(setter) Assert.Equal("set_" & fieldName, setter.Name) Else Assert.True([property].IsReadOnly) End If ' Do we actually need this?? 'Dim field As FieldSymbol = anonymousType.GetMember(Of FieldSymbol)("$" & fieldName) 'Assert.NotNull(field) 'Assert.Equal("$" & fieldName, field.Name) 'Assert.Equal(isKey, field.IsReadOnly) End Sub Private Function Compile(text As XElement, ByRef tree As SyntaxTree, nodes As List(Of SyntaxNode), Optional errors As XElement = Nothing) As VisualBasicCompilation Dim spans As New List(Of TextSpan) ExtractTextIntervals(text, spans) Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(text, {SystemRef, SystemCoreRef, MsvbRef}) If errors Is Nothing Then CompilationUtils.AssertNoErrors(compilation) Else CompilationUtils.AssertTheseDiagnostics(compilation, errors) End If tree = compilation.SyntaxTrees(0) For Each span In spans Dim stack As New Stack(Of SyntaxNode) stack.Push(tree.GetRoot()) While stack.Count > 0 Dim node = stack.Pop() If span.Contains(node.Span) Then nodes.Add(node) Exit While End If For Each child In node.ChildNodes stack.Push(child) Next End While Next Return compilation End Function Private Shared Sub ExtractTextIntervals(text As XElement, nodes As List(Of TextSpan)) text.<file>.Value = text.<file>.Value.Trim().Replace(vbLf, vbCrLf) Dim index As Integer = 0 Do Dim startMarker = "[#" & index Dim endMarker = index & "#]" ' opening '[#{0-9}' Dim start = text.<file>.Value.IndexOf(startMarker, StringComparison.Ordinal) If start < 0 Then Exit Do End If ' closing '{0-9}#]' Dim [end] = text.<file>.Value.IndexOf(endMarker, StringComparison.Ordinal) Assert.InRange([end], 0, Int32.MaxValue) nodes.Add(New TextSpan(start, [end] - start + 3)) text.<file>.Value = text.<file>.Value.Replace(startMarker, " ").Replace(endMarker, " ") index += 1 Assert.InRange(index, 0, 9) Loop End Sub Private Shared Function GetNamedTypeSymbol(c As VisualBasicCompilation, namedTypeName As String, Optional fromCorLib As Boolean = False) As NamedTypeSymbol Dim nameParts = namedTypeName.Split("."c) Dim srcAssembly = DirectCast(c.Assembly, SourceAssemblySymbol) Dim nsSymbol As NamespaceSymbol = (If(fromCorLib, srcAssembly.CorLibrary, srcAssembly)).GlobalNamespace For Each ns In nameParts.Take(nameParts.Length - 1) nsSymbol = DirectCast(nsSymbol.GetMember(ns), NamespaceSymbol) Next Return DirectCast(nsSymbol.GetTypeMember(nameParts(nameParts.Length - 1)), NamedTypeSymbol) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Test/ProjectSystemShim/MockRuleSetFile.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 Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim Public Class MockRuleSetFile Implements IRuleSetFile Private ReadOnly _generalOption As ReportDiagnostic Private ReadOnly _specificOptions As ImmutableDictionary(Of String, ReportDiagnostic) Public Sub New(generalOption As ReportDiagnostic, specificOptions As ImmutableDictionary(Of String, ReportDiagnostic)) _generalOption = generalOption _specificOptions = specificOptions End Sub Public ReadOnly Property FilePath As String Implements IRuleSetFile.FilePath Get Throw New NotImplementedException() End Get End Property Public Event UpdatedOnDisk As EventHandler Implements IRuleSetFile.UpdatedOnDisk Public Function GetException() As Exception Implements IRuleSetFile.GetException Throw New NotImplementedException() End Function Public Function GetGeneralDiagnosticOption() As ReportDiagnostic Implements IRuleSetFile.GetGeneralDiagnosticOption Return _generalOption End Function Public Function GetSpecificDiagnosticOptions() As ImmutableDictionary(Of String, ReportDiagnostic) Implements IRuleSetFile.GetSpecificDiagnosticOptions Return _specificOptions 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 Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim Public Class MockRuleSetFile Implements IRuleSetFile Private ReadOnly _generalOption As ReportDiagnostic Private ReadOnly _specificOptions As ImmutableDictionary(Of String, ReportDiagnostic) Public Sub New(generalOption As ReportDiagnostic, specificOptions As ImmutableDictionary(Of String, ReportDiagnostic)) _generalOption = generalOption _specificOptions = specificOptions End Sub Public ReadOnly Property FilePath As String Implements IRuleSetFile.FilePath Get Throw New NotImplementedException() End Get End Property Public Event UpdatedOnDisk As EventHandler Implements IRuleSetFile.UpdatedOnDisk Public Function GetException() As Exception Implements IRuleSetFile.GetException Throw New NotImplementedException() End Function Public Function GetGeneralDiagnosticOption() As ReportDiagnostic Implements IRuleSetFile.GetGeneralDiagnosticOption Return _generalOption End Function Public Function GetSpecificDiagnosticOptions() As ImmutableDictionary(Of String, ReportDiagnostic) Implements IRuleSetFile.GetSpecificDiagnosticOptions Return _specificOptions End Function End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Test/Symbol/Symbols/ArrayTypeSymbolTests.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.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ArrayTypeSymbolTests : CSharpTestBase { [Fact(), WorkItem(546670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546670")] public void MissingIList() { var c = CreateEmptyCompilation(@" public class X { public static int[] A; } ", new[] { MinCorlibRef }); var field = c.GlobalNamespace.GetMember<NamedTypeSymbol>("X").GetMember<FieldSymbol>("A"); Assert.Equal(0, field.Type.Interfaces().Length); c.VerifyDiagnostics(); } } }
// 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.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class ArrayTypeSymbolTests : CSharpTestBase { [Fact(), WorkItem(546670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546670")] public void MissingIList() { var c = CreateEmptyCompilation(@" public class X { public static int[] A; } ", new[] { MinCorlibRef }); var field = c.GlobalNamespace.GetMember<NamedTypeSymbol>("X").GetMember<FieldSymbol>("A"); Assert.Equal(0, field.Type.Interfaces().Length); c.VerifyDiagnostics(); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/CSharp/Test/Semantic/Semantics/GenericConstraintsTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class GenericConstraintsTests : CompilingTestBase { [Fact] public void EnumConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (13,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(13, 26), // (14,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_Interface() { CreateCompilation(@" public class Test<T> where T : System.Enum, System.IDisposable { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.IDisposable { var a = new Test<E1>(); // not disposable var b = new Test<U>(); // not enum var c = new Test<int>(); // neither disposable nor enum } }").VerifyDiagnostics( // (13,26): error CS0315: The type 'E1' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'E1' to 'System.IDisposable'. // var a = new Test<E1>(); // not disposable Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E1").WithArguments("Test<T>", "System.IDisposable", "T", "E1").WithLocation(13, 26), // (14,26): error CS0314: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion or type parameter conversion from 'U' to 'System.Enum'. // var b = new Test<U>(); // not enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "U").WithArguments("Test<T>", "System.Enum", "T", "U").WithLocation(14, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(15, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.IDisposable'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.IDisposable", "T", "int").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): 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 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Enum, new() { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26), // (15,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (11,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(11, 26), // (12,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ValueType() { var reference = CreateCompilation(@" public class Test<T> where T : struct, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): 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 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum, new() { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26), // (13,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Enum { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'enum generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Enum").WithArguments("enum generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" enum E { } class Legacy { void M() { var a = new Test<E>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (10,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Enum'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Enum", "T", "Legacy").WithLocation(10, 26)); } [Theory] [InlineData("byte")] [InlineData("sbyte")] [InlineData("short")] [InlineData("ushort")] [InlineData("int")] [InlineData("uint")] [InlineData("long")] [InlineData("ulong")] public void EnumConstraint_DifferentBaseTypes(string type) { CreateCompilation($@" public class Test<T> where T : System.Enum {{ }} public enum E1 : {type} {{ A }} public class Test2 {{ public void M() {{ var a = new Test<E1>(); // Valid var b = new Test<int>(); // Invalid }} }} ").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26)); } [Fact] public void EnumConstraint_InheritanceChain() { CreateCompilation(@" public enum E { A } public class Test<T, U> where U : System.Enum, T { } public class Test2 { public void M() { var a = new Test<Test2, E>(); var b = new Test<E, E>(); var c = new Test<System.Enum, System.Enum>(); var d = new Test<E, System.Enum>(); var e = new Test<System.Enum, E>(); } }").VerifyDiagnostics( // (13,33): error CS0315: The type 'E' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no boxing conversion from 'E' to 'Test2'. // var a = new Test<Test2, E>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E").WithArguments("Test<T, U>", "Test2", "U", "E").WithLocation(13, 33), // (18,29): error CS0311: The type 'System.Enum' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Enum' to 'E'. // var d = new Test<E, System.Enum>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Enum").WithArguments("Test<T, U>", "E", "U", "System.Enum").WithLocation(18, 29)); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ValueType() { var code = "public class Test<T> where T : struct, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.True(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Enum, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }").VerifyDiagnostics( // (12,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(12, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }", references: new[] { reference }).VerifyDiagnostics( // (8,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(8, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Enum { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(8, 43)); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Enum { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(4, 43)); } [Fact] public void EnumConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public enum MyEnum { } public abstract class A<T> { public abstract void F<U>() where U : System.Enum, T; } public class B : A<MyEnum> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Enum", "MyEnum" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Enum { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Enum' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Enum").WithArguments("Enum", "System").WithLocation(7, 39)); } [Fact] public void EnumConstraint_BindingToMethods() { var code = @" enum A : short { a } enum B : uint { b } class Test { public static void Main() { Print(A.a); Print(B.b); } static void Print<T>(T obj) where T : System.Enum { System.Console.WriteLine(obj.GetTypeCode()); } }"; CompileAndVerify(code, expectedOutput: @" Int16 UInt32"); } [Fact] public void EnumConstraint_InheritingFromEnum() { var code = @" public class Child : System.Enum { } public enum E { A } public class Test { public void M<T>(T arg) where T : System.Enum { } public void N() { M(E.A); // valid M(new Child()); // invalid } }"; CreateCompilation(code).VerifyDiagnostics( // (2,22): error CS0644: 'Child' cannot derive from special class 'Enum' // public class Child : System.Enum Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.Enum").WithArguments("Child", "System.Enum").WithLocation(2, 22), // (20,9): error CS0311: The type 'Child' cannot be used as type parameter 'T' in the generic type or method 'Test.M<T>(T)'. There is no implicit reference conversion from 'Child' to 'System.Enum'. // M(new Child()); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Test.M<T>(T)", "System.Enum", "T", "Child").WithLocation(20, 9)); } [Fact] public void DelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Delegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(2, 40) ); } [Fact] public void DelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Delegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Delegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Delegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Delegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.Delegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.Delegate, System.Delegate>(); var d = new Test<System.MulticastDelegate, System.Delegate>(); var e = new Test<System.Delegate, System.MulticastDelegate>(); var f = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var g = new Test<D1, System.Delegate>(); var h = new Test<System.Delegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (14,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var d = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(14, 52), // (18,30): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'D1'. // var g = new Test<D1, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "D1", "U", "System.Delegate").WithLocation(18, 30)); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.Delegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Delegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Delegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(8, 43)); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Delegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(4, 43)); } [Fact] public void DelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.Delegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Delegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Delegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Delegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Delegate").WithArguments("Delegate", "System").WithLocation(7, 39)); } [Fact] public void DelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.Delegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void MulticastDelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.MulticastDelegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(2, 40) ); } [Fact] public void MulticastDelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.MulticastDelegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.MulticastDelegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.MulticastDelegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.MulticastDelegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.MulticastDelegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var d = new Test<System.Delegate, System.MulticastDelegate>(); var e = new Test<System.MulticastDelegate, System.Delegate>(); var f = new Test<System.Delegate, System.Delegate>(); var g = new Test<D1, System.MulticastDelegate>(); var h = new Test<System.MulticastDelegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (15,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var e = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(15, 52), // (16,43): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var f = new Test<System.Delegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(16, 43), // (18,30): error CS0311: The type 'System.MulticastDelegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.MulticastDelegate' to 'D1'. // var g = new Test<D1, System.MulticastDelegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.MulticastDelegate").WithArguments("Test<T, U>", "D1", "U", "System.MulticastDelegate").WithLocation(18, 30)); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.MulticastDelegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.MulticastDelegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(8, 43)); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(4, 43)); } [Fact] public void MulticastDelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.MulticastDelegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.MulticastDelegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.MulticastDelegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'MulticastDelegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MulticastDelegate").WithArguments("MulticastDelegate", "System").WithLocation(7, 39)); } [Fact] public void MulticastDelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.MulticastDelegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void ConversionInInheritanceChain_MulticastDelegate() { var code = @" class A<T> where T : System.Delegate { } class B<T> : A<T> where T : System.MulticastDelegate { }"; CreateCompilation(code).VerifyDiagnostics(); code = @" class A<T> where T : System.MulticastDelegate { } class B<T> : A<T> where T : System.Delegate { }"; CreateCompilation(code).VerifyDiagnostics( // (3,7): error CS0311: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. There is no implicit reference conversion from 'T' to 'System.MulticastDelegate'. // class B<T> : A<T> where T : System.Delegate { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("A<T>", "System.MulticastDelegate", "T", "T").WithLocation(3, 7)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Type() { CreateCompilation(@" public class Test<T> where T : unmanaged { } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (12,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(12, 26), // (13,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (16,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(16, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Method() { CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(13, 28), // (14,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(14, 28), // (17,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(17, 28) ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Delegate() { CreateCompilation(@" public delegate void D<T>() where T : unmanaged; public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }").VerifyDiagnostics( // (8,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(8, 32), // (9,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(9, 31), // (12,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(12, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_LocalFunction() { CreateCompilation(@" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { void M<T>() where T : unmanaged { } M<GoodType>(); // unmanaged struct M<BadType>(); // managed struct M<string>(); // reference type M<int>(); // value type M<U>(); // generic type constrained to unmanaged M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,9): error CS8377: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("M<T>()", "T", "BadType").WithLocation(13, 9), // (14,9): error CS8377: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("M<T>()", "T", "string").WithLocation(14, 9), // (17,9): error CS8377: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("M<T>()", "T", "W").WithLocation(17, 9)); } [Fact] public void UnmanagedConstraint_Compilation_ReferenceType() { var c = CreateCompilation("public class Test<T> where T : class, unmanaged {}"); c.VerifyDiagnostics( // (1,39): error CS0449: The 'unmanaged' constraint cannot be combined with the 'class' constraint // public class Test<T> where T : class, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 39)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_ValueType() { var c = CreateCompilation("public class Test<T> where T : struct, unmanaged {}"); c.VerifyDiagnostics( // (1,40): error CS0449: The 'unmanaged' constraint cannot be combined with the 'struct' constraint // public class Test<T> where T : struct, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 40)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_Constructor() { CreateCompilation("public class Test<T> where T : unmanaged, new() {}").VerifyDiagnostics( // (1,43): error CS8379: The 'new()' constraint cannot be used with the 'unmanaged' constraint // public class Test<T> where T : unmanaged, new() {} Diagnostic(ErrorCode.ERR_NewBoundWithUnmanaged, "new").WithLocation(1, 43)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_Before() { CreateCompilation("public class Test<T> where T : unmanaged, System.Exception { }").VerifyDiagnostics( // (1,43): error CS8380: 'Exception': cannot specify both a constraint class and the 'unmanaged' constraint // public class Test<T> where T : unmanaged, System.Exception { } Diagnostic(ErrorCode.ERR_UnmanagedBoundWithClass, "System.Exception").WithArguments("System.Exception").WithLocation(1, 43) ); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_After() { CreateCompilation("public class Test<T> where T : System.Exception, unmanaged { }").VerifyDiagnostics( // (1,50): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Exception, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 50)); } [Fact] public void UnmanagedConstraint_Compilation_OtherValidTypes_After() { CreateCompilation("public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { }").VerifyDiagnostics( // (1,65): error CS8376: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 65)); } [Fact] public void UnmanagedConstraint_OtherValidTypes_Before() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertEx.Equal(new string[] { "Enum", "IDisposable" }, typeParameter.ConstraintTypes().Select(type => type.Name)); }; CompileAndVerify( "public class Test<T> where T : unmanaged, System.Enum, System.IDisposable { }", sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_After() { CreateCompilation("public class Test<T, U> where T : U, unmanaged { }").VerifyDiagnostics( // (1,38): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T, U> where T : U, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 38)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_Before() { CreateCompilation("public class Test<T, U> where T : unmanaged, U { }").VerifyDiagnostics(); CreateCompilation("public class Test<T, U> where U: class where T : unmanaged, U, System.IDisposable { }").VerifyDiagnostics(); } [Fact] public void UnmanagedConstraint_UnmanagedEnumNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class ValueType {} } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (8,32): error CS0518: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType").WithLocation(8, 32)); } [Fact] public void UnmanagedConstraint_ValueTypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class Enum {} public class Int32 {} namespace Runtime { namespace InteropServices { public enum UnmanagedType {} } } } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (16,32): error CS0518: Predefined type 'System.ValueType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.ValueType").WithLocation(16, 32)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Type() { var reference = CreateCompilation(@" public class Test<T> where T : unmanaged { }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(9, 26), // (10,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(10, 26), // (13,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(13, 26)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Method() { var reference = CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(9, 28), // (10,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(10, 28), // (13,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(13, 28) ); } [Fact] public void UnmanagedConstraint_Reference_Alone_Delegate() { var reference = CreateCompilation(@" public delegate void D<T>() where T : unmanaged; ").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (7,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(7, 32), // (8,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(8, 31), // (11,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(11, 26)); } [Fact] public void UnmanagedConstraint_Before_7_3() { var code = @" public class Test<T> where T : unmanaged { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'unmanaged generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "unmanaged").WithArguments("unmanaged generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" class Legacy { void M() { var a = new Test<int>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS8377: The type 'Legacy' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Legacy").WithArguments("Test<T>", "T", "Legacy").WithLocation(7, 26)); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Type() { var code = "public class Test<T> where T : unmanaged { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } }"; CompileAndVerify(code, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" struct Test { public string RefMember { get; set; } } public abstract class A { public abstract void M<T>() where T : unmanaged; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }").VerifyDiagnostics( // (17,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(17, 14), // (18,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(18, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : unmanaged; }").EmitToImageReference(); CreateCompilation(@" struct Test { public string RefMember { get; set; } } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }", references: new[] { reference }).VerifyDiagnostics( // (13,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(13, 14), // (14,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(14, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : unmanaged { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(8, 43)); } [Fact] public void UnmanagedConstraint_StructMismatchInImplements() { CreateCompilation(@" public struct Segment<T> { public T[] array; } public interface I1<in T> where T : unmanaged { void Test<G>(G x) where G : unmanaged; } public class C2<T> : I1<T> where T : struct { public void Test<G>(G x) where G : struct { I1<T> i = this; i.Test(default(Segment<int>)); } } ").VerifyDiagnostics( // (11,14): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // public class C2<T> : I1<T> where T : struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "T").WithLocation(11, 14), // (13,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : struct Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(13, 17), // (15,12): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // I1<T> i = this; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "T").WithArguments("I1<T>", "T", "T").WithLocation(15, 12), // (16,11): error CS8377: The type 'Segment<int>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)' // i.Test(default(Segment<int>)); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Test").WithArguments("I1<T>.Test<G>(G)", "G", "Segment<int>").WithLocation(16, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplements() { CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } } ").VerifyDiagnostics( // (7,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(7, 14), // (9,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(9, 17), // (11,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(11, 12), // (13,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(13, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta() { var reference = CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } ").EmitToImageReference(); CreateCompilation(@" public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } }", references: new[] { reference }).VerifyDiagnostics( // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(2, 14), // (4,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(4, 17), // (6,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(6, 12), // (8,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(8, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta2() { var reference = CreateCompilation(@" public interface I1 { void Test<G>(ref G x) where G : unmanaged, System.IDisposable; } ").EmitToImageReference(); var reference1 = CreateCompilation(@" public class C1 : I1 { void I1.Test<G>(ref G x) { x.Dispose(); } }", references: new[] { reference }).EmitToImageReference(); ; CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } class Test { static void Main() { S local = default; I1 i = new C1(); i.Test(ref local); System.Console.WriteLine(local.a); } }", // NOTE: must pass verification (IDisposable constraint is copied over to the implementing method) options: TestOptions.UnsafeReleaseExe, references: new[] { reference, reference1 }, verify: Verification.Passes, expectedOutput: "123"); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : unmanaged { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(4, 43)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerOperations_Invalid() { CreateCompilation(@" class Test { void M<T>(T arg) where T : unmanaged { } void N() { M(""test""); } }").VerifyDiagnostics( // (9,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(9, 9)); } [ConditionalTheory(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [InlineData("(sbyte)1", "System.SByte", 1)] [InlineData("(byte)1", "System.Byte", 1)] [InlineData("(short)1", "System.Int16", 2)] [InlineData("(ushort)1", "System.UInt16", 2)] [InlineData("(int)1", "System.Int32", 4)] [InlineData("(uint)1", "System.UInt32", 4)] [InlineData("(long)1", "System.Int64", 8)] [InlineData("(ulong)1", "System.UInt64", 8)] [InlineData("'a'", "System.Char", 2)] [InlineData("(float)1", "System.Single", 4)] [InlineData("(double)1", "System.Double", 8)] [InlineData("(decimal)1", "System.Decimal", 16)] [InlineData("false", "System.Boolean", 1)] [InlineData("E.A", "E", 4)] [InlineData("new S { a = 1, b = 2, c = 3 }", "S", 12)] public void UnmanagedConstraints_PointerOperations_SimpleTypes(string arg, string type, int size) { CompileAndVerify(@" enum E { A } struct S { public int a; public int b; public int c; } unsafe class Test { static T* M<T>(T arg) where T : unmanaged { T* ptr = &arg; System.Console.WriteLine(ptr->GetType()); // method access System.Console.WriteLine(sizeof(T)); // sizeof operator T* ar = stackalloc T [10]; return ar; } static void Main() { M(" + arg + @"); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: string.Join(Environment.NewLine, type, size)).VerifyIL("Test.M<T>", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: conv.u IL_0003: constrained. ""T"" IL_0009: callvirt ""System.Type object.GetType()"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: sizeof ""T"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ldc.i4.s 10 IL_0020: conv.u IL_0021: sizeof ""T"" IL_0027: mul.ovf.un IL_0028: localloc IL_002a: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_InterfaceMethod() { CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } unsafe class Test { static void M<T>(ref T arg) where T : unmanaged, System.IDisposable { arg.Dispose(); fixed(T* ptr = &arg) { ptr->Dispose(); } } static void Main() { S local = default; M(ref local); System.Console.WriteLine(local.a); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "246").VerifyIL("Test.M<T>", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (pinned T& V_0) IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: callvirt ""void System.IDisposable.Dispose()"" IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: conv.u IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ldc.i4.0 IL_001c: conv.u IL_001d: stloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CtorAndValueTypeAreEmitted() { CompileAndVerify(@" using System.Linq; class Program { public static void M<T>() where T: unmanaged { } static void Main(string[] args) { var typeParam = typeof(Program).GetMethod(""M"").GetGenericArguments().First(); System.Console.WriteLine(typeParam.GenericParameterAttributes); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "NotNullableValueTypeConstraint, DefaultConstructorConstraint"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Flat() { CompileAndVerify(@" struct TestData { public int A; public TestData(int a) { A = a; } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "4"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Nested() { CompileAndVerify(@" struct InnerTestData { public int B; public InnerTestData(int b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, int b) { A = a; B = new InnerTestData(b); } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "8"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Error() { CreateCompilation(@" struct InnerTestData { public string B; public InnerTestData(string b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, string b) { A = a; B = new InnerTestData(b); } } class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { } }").VerifyDiagnostics( // (24,9): error CS8379: The type 'TestData' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.N<T>()' // N<TestData>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "N<TestData>").WithArguments("Test.N<T>()", "T", "TestData").WithLocation(24, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_InScope() { CompileAndVerify(@" class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } class Test { public static void Main() { M(new unmanaged()); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }", expectedOutput: "success"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_OutOfScope() { CreateCompilation(@" namespace hidden { class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } } class Test { public static void Main() { M(""test""); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }").VerifyDiagnostics( // (16,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(16, 9), // (20,13): error CS1061: 'T' does not contain a definition for 'Print' and no extension method 'Print' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.Print(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Print").WithArguments("T", "Print").WithLocation(20, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Methods() { CompileAndVerify(@" class Program { static void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } static void B<T>(T arg) where T : unmanaged { A(arg); } static void Main() { B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Types() { CompileAndVerify(@" class A<T> where T : struct { public void M(T arg) { System.Console.WriteLine(arg); } } class B<T> : A<T> where T : unmanaged { } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Interfaces() { CompileAndVerify(@" interface A<T> where T : struct { void M(T arg); } class B<T> : A<T> where T : unmanaged { public void M(T arg) { System.Console.WriteLine(arg); } } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_LocalFunctions() { CompileAndVerify(@" class Program { static void Main() { void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } void B<T>(T arg) where T : unmanaged { A(arg); } B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerTypeSubstitution() { var compilation = CreateCompilation(@" unsafe public class Test { public T* M<T>() where T : unmanaged => throw null; public void N() { var result = M<int>(); } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var value = ((VariableDeclaratorSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.VariableDeclarator)).Initializer.Value; Assert.Equal("M<int>()", value.ToFullString()); var symbol = (IMethodSymbol)model.GetSymbolInfo(value).Symbol; Assert.Equal("System.Int32*", symbol.ReturnType.ToTestDisplayString()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CannotConstraintToTypeParameterConstrainedByUnmanaged() { CreateCompilation(@" class Test<U> where U : unmanaged { void M<T>() where T : U { } }").VerifyDiagnostics( // (4,12): error CS8379: Type parameter 'U' has the 'unmanaged' constraint so 'U' cannot be used as a constraint for 'T' // void M<T>() where T : U Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "T").WithArguments("T", "U").WithLocation(4, 12)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedAsTypeConstraintName() { CreateCompilation(@" class Test<unmanaged> where unmanaged : System.IDisposable { void M<T>(T arg) where T : unmanaged { arg.Dispose(); arg.NonExistentMethod(); } }").VerifyDiagnostics( // (7,13): error CS1061: 'T' does not contain a definition for 'NonExistentMethod' and no extension method 'NonExistentMethod' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.NonExistentMethod(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "NonExistentMethod").WithArguments("T", "NonExistentMethod").WithLocation(7, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CircularReferenceToUnmanagedTypeWillBindSuccessfully() { CreateCompilation(@" public unsafe class C<U> where U : unmanaged { public void M1<T>() where T : T* { } public void M2<T>() where T : U* { } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M2<T>() where T : U* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(5, 35), // (4,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M1<T>() where T : T* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "T*").WithLocation(4, 35)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_EnumWithUnmanaged() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal("Enum", typeParameter.ConstraintTypes().Single().Name); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); }; CompileAndVerify( source: "public class Test<T> where T : unmanaged, System.Enum {}", sourceSymbolValidator: validator, symbolValidator: validator); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedInGenericType() { var code = @" public class Wrapper<T> { public enum E { } public struct S { } } public class Test { void IsUnmanaged<T>() where T : unmanaged { } void IsEnum<T>() where T : System.Enum { } void IsStruct<T>() where T : struct { } void IsNew<T>() where T : new() { } void User() { IsUnmanaged<Wrapper<int>.E>(); IsEnum<Wrapper<int>.E>(); IsStruct<Wrapper<int>.E>(); IsNew<Wrapper<int>.E>(); IsUnmanaged<Wrapper<int>.S>(); IsEnum<Wrapper<int>.S>(); // Invalid IsStruct<Wrapper<int>.S>(); IsNew<Wrapper<int>.S>(); IsUnmanaged<Wrapper<string>.E>(); IsEnum<Wrapper<string>.E>(); IsStruct<Wrapper<string>.E>(); IsNew<Wrapper<string>.E>(); IsUnmanaged<Wrapper<string>.S>(); IsEnum<Wrapper<string>.S>(); // Invalid IsStruct<Wrapper<string>.S>(); IsNew<Wrapper<string>.S>(); } }"; CreateCompilation(code).VerifyDiagnostics( // (28,9): error CS0315: The type 'Wrapper<int>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<int>.S' to 'System.Enum'. // IsEnum<Wrapper<int>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<int>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<int>.S").WithLocation(28, 9), // (38,9): error CS0315: The type 'Wrapper<string>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<string>.S' to 'System.Enum'. // IsEnum<Wrapper<string>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<string>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<string>.S").WithLocation(38, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerInsideStruct() { CompileAndVerify(@" unsafe struct S { public int a; public int* b; public S(int a, int* b) { this.a = a; this.b = b; } } unsafe class Test { static T* M<T>() where T : unmanaged { System.Console.WriteLine(typeof(T).FullName); T* ar = null; return ar; } static void Main() { S* ar = M<S>(); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "S"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_LambdaTypeParameters() { CompileAndVerify(@" public delegate T D<T>() where T : unmanaged; public class Test<U1> where U1 : unmanaged { public static void Print<T>(D<T> lambda) where T : unmanaged { System.Console.WriteLine(lambda()); } public static void User1(U1 arg) { Print(() => arg); } public static void User2<U2>(U2 arg) where U2 : unmanaged { Print(() => arg); } } public class Program { public static void Main() { // Testing the constraint when the lambda type parameter is both coming from an enclosing type, or copied to the generated lambda class Test<int>.User1(1); Test<int>.User2(2); } }", expectedOutput: @" 1 2", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.True(module.ContainingAssembly.GetTypeByMetadataName("D`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").GetTypeMember("<>c__DisplayClass2_0").TypeParameters.Single().HasUnmanagedTypeConstraint); }); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_IsConsideredDuringOverloadResolution() { CompileAndVerify(@" public class Program { static void Test<T>(T arg) where T : unmanaged { System.Console.WriteLine(""Unmanaged: "" + arg); } static void Test(object arg) { System.Console.WriteLine(""Object: "" + arg); } static void User<U>(U arg) where U : unmanaged { Test(1); // should pick up the first, as it is better than the second one (which requires a conversion) Test(""2""); // should pick up the second, as it is the only candidate Test(arg); // should pick up the first, as it is the only candidate } static void Main() { User(3); } }", expectedOutput: @" Unmanaged: 1 Object: 2 Unmanaged: 3"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { var p = stackalloc T[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_CallFromADifferentMethod() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { } unsafe void N() { var p = stackalloc int[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { M(null, b); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs_CallFromADifferentMethod() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { } static void N() { M(null, 5); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_Errors() { CreateCompilation(@" unsafe class C { void Unmanaged<T>(T* a) where T : unmanaged { } void UnmanagedWithInterface<T>(T* a) where T : unmanaged, System.IDisposable { } void Test() { int a = 0; Unmanaged(0); // fail (type inference) Unmanaged(a); // fail (type inference) Unmanaged(&a); // succeed (unmanaged type pointer) UnmanagedWithInterface(0); // fail (type inference) UnmanagedWithInterface(a); // fail (type inference) UnmanagedWithInterface(&a); // fail (does not match interface) } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (14,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(14, 9), // (15,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(15, 9), // (18,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(19, 9), // (20,9): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'C.UnmanagedWithInterface<T>(T*)'. There is no boxing conversion from 'int' to 'System.IDisposable'. // UnmanagedWithInterface(&a); // fail (does not match interface) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)", "System.IDisposable", "T", "int").WithLocation(20, 9)); } [Fact] public void UnmanagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void ManagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2<T>(MyStruct<T>* ms) where T : unmanaged { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12)); } [Fact] public void UnmanagedGenericConstraintStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct OuterStruct { public int x; public InnerStruct inner; } public struct InnerStruct { public int y; } public class C { public unsafe void M() { MyStruct<OuterStruct> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<OuterStruct>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedGenericStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18), // (17,12): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M2(&myStruct); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&myStruct").WithArguments("unmanaged constructed types", "8.0").WithLocation(17, 12), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55)); } [Fact] public void UnmanagedGenericStructMultipleConstraints() { // A diagnostic will only be produced for the first violated constraint. var code = @" public struct MyStruct<T> where T : unmanaged, System.IDisposable { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct = default; _ = myStruct; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (16,18): error CS0315: The type 'InnerStruct<int>' cannot be used as type parameter 'T' in the generic type or method 'MyStruct<T>'. There is no boxing conversion from 'InnerStruct<int>' to 'System.IDisposable'. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "InnerStruct<int>").WithArguments("MyStruct<T>", "System.IDisposable", "T", "InnerStruct<int>").WithLocation(16, 18) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18) ); } [Fact] public void UnmanagedGenericConstraintPartialConstructedStruct() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M<U>() { MyStruct<U> myStruct; M2<U>(&myStruct); } public unsafe void M2<V>(MyStruct<V>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (11,18): error CS8377: The type 'U' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // MyStruct<U> myStruct; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "U").WithArguments("MyStruct<T>", "T", "U").WithLocation(11, 18), // (12,15): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<U>') // M2<U>(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<U>").WithLocation(12, 15), // (15,43): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<V>') // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<V>").WithLocation(15, 43), // (15,43): error CS8377: The type 'V' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "ms").WithArguments("MyStruct<T>", "T", "V").WithLocation(15, 43)); } [Fact] public void GenericStructManagedFieldPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<string>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12), // (15,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // public unsafe void M2(MyStruct<string>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<string>").WithLocation(15, 45)); } [Fact] public void UnmanagedRecursiveGenericStruct() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public YourStruct<T>* field; } public unsafe struct YourStruct<T> where T : unmanaged { public MyStruct<T>* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveStruct() { var code = @" public unsafe struct MyStruct { public YourStruct* field; } public unsafe struct YourStruct { public MyStruct* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgument() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedCyclic() { var code = @" public struct MyStruct<T> { public YourStruct<T> field; } public struct YourStruct<T> where T : unmanaged { public MyStruct<T> field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,26): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<T>' causes a cycle in the struct layout // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<T>").WithLocation(4, 26), // (4,26): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "T").WithLocation(4, 26), // (9,24): error CS0523: Struct member 'YourStruct<T>.field' of type 'MyStruct<T>' causes a cycle in the struct layout // public MyStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("YourStruct<T>.field", "MyStruct<T>").WithLocation(9, 24)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentManagedGenericField() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public T myField; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentConstraintViolation() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public string s; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveTypeArgumentConstraintViolation_02() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; public string s; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.True(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void NestedGenericStructContainingPointer() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T* field; public T this[int index] { get { return field[index]; } } } public class C { public static unsafe void Main() { float f = 42; var ms = new MyStruct<float> { field = &f }; var test = new MyStruct<MyStruct<float>> { field = &ms }; float value = test[0][0]; System.Console.Write(value); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, expectedOutput: "42", verify: Verification.Skipped); } [Fact] public void SimpleGenericStructPointer_ILValidation() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T field; public static void Test() { var ms = new MyStruct<int>(); MyStruct<int>* ptr = &ms; ptr->field = 42; } } "; var il = @" { // Code size 19 (0x13) .maxstack 2 .locals init (MyStruct<int> V_0) //ms IL_0000: ldloca.s V_0 IL_0002: initobj ""MyStruct<int>"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: ldc.i4.s 42 IL_000d: stfld ""int MyStruct<int>.field"" IL_0012: ret } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseDll, verify: Verification.Skipped) .VerifyIL("MyStruct<T>.Test", il); } [Fact, WorkItem(31439, "https://github.com/dotnet/roslyn/issues/31439")] public void CircularTypeArgumentUnmanagedConstraint() { var code = @" public struct X<T> where T : unmanaged { } public struct Z { public X<Z> field; }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("Z").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void GenericStructAddressOfRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var ms = new MyStruct<int>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var ptr = &ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 19) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructFixedRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Test(MyClass c) { fixed (MyStruct<int>* ptr = &c.ms) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,16): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>*").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 16), // (12,37): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&c.ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 37)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructSizeofRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var size = sizeof(MyStruct<int>); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,20): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var size = sizeof(MyStruct<int>); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "sizeof(MyStruct<int>)").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 20) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericImplicitStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc[] { new MyStruct<int>() }; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc[] { new MyStruct<int>() }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc[] { new MyStruct<int>() }").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 19)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc MyStruct<int>[4]; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,30): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc MyStruct<int>[4]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 30)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public unsafe struct OtherStruct { public MyStruct<int>* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,27): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 27) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericNestedStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public struct InnerStruct { public T field; } } public unsafe struct OtherStruct { public MyStruct<int>.InnerStruct* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,39): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>.InnerStruct* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 39) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingTuple_Unmanaged_RequiresCSharp8() { var code = @" public struct MyStruct { public (int, int) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2() { M<MyStruct>(); M<(int, int)>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (14,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<(int, int)>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<(int, int)>").WithArguments("unmanaged constructed types", "8.0").WithLocation(14, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingGenericTuple_Unmanaged() { var code = @" public struct MyStruct<T> { public (T, T) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2<U>() where U : unmanaged { M<MyStruct<U>>(); } public void M3<V>() { M<MyStruct<V>>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct<U>>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct<U>>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); } [Fact] public void GenericRefStructAddressOf_01() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>() { field = 42 }; var ptr = &ms; System.Console.Write(ptr->field); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericRefStructAddressOf_02() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public unsafe void M() { var ms = new MyStruct<object>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<object>') // var ptr = &ms; Diagnostic(ErrorCode.ERR_ManagedAddr, "&ms").WithArguments("MyStruct<object>").WithLocation(12, 19) ); } [Fact] public void GenericStructFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Main() { var c = new MyClass(); c.ms.field = 42; fixed (MyStruct<int>* ptr = &c.ms) { System.Console.Write(ptr->field); } } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericStructLocalFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>(); fixed (int* ptr = &ms.field) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,27): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* ptr = &ms.field) Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&ms.field").WithLocation(12, 27) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics() { var comp = CreateCompilation(@" class C1<T1> where T1 : class, struct, unmanaged, notnull { void M1<T2>() where T2 : class, struct, unmanaged, notnull {} } class C2<T1> where T1 : struct, class, unmanaged, notnull { void M2<T2>() where T2 : struct, class, unmanaged, notnull {} } class C3<T1> where T1 : class, class { void M3<T2>() where T2 : class, class {} } "); comp.VerifyDiagnostics( // (2,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(2, 32), // (2,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(2, 40), // (2,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(2, 51), // (4,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(4, 37), // (4,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(4, 45), // (4,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 56), // (6,33): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(6, 33), // (6,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(6, 40), // (6,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(6, 51), // (8,38): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 38), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(8, 45), // (8,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(8, 56), // (10,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C3<T1> where T1 : class, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(10, 32), // (12,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M3<T2>() where T2 : class, class {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(12, 37) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics_InheritedClassStruct() { var comp = CreateCompilation(@" class C { public virtual void M<T1>() where T1 : class {} } class D : C { public override void M<T1>() where T1 : C, class, struct {} } class E { public virtual void M<T2>() where T2 : struct {} } class F : E { public override void M<T2>() where T2 : E, struct, class {} } class G { public virtual void M<T3>() where T3 : unmanaged {} } class H : G { public override void M<T3>() where T3 : G, unmanaged, struct {} } "); comp.VerifyDiagnostics( // (8,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T1>() where T1 : C, class, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "C").WithLocation(8, 45), // (16,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T2>() where T2 : E, struct, class {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "E").WithLocation(16, 45), // (24,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T3>() where T3 : G, unmanaged, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "G").WithLocation(24, 45) ); } } }
// 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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class GenericConstraintsTests : CompilingTestBase { [Fact] public void EnumConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (13,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(13, 26), // (14,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_Interface() { CreateCompilation(@" public class Test<T> where T : System.Enum, System.IDisposable { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.IDisposable { var a = new Test<E1>(); // not disposable var b = new Test<U>(); // not enum var c = new Test<int>(); // neither disposable nor enum } }").VerifyDiagnostics( // (13,26): error CS0315: The type 'E1' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'E1' to 'System.IDisposable'. // var a = new Test<E1>(); // not disposable Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E1").WithArguments("Test<T>", "System.IDisposable", "T", "E1").WithLocation(13, 26), // (14,26): error CS0314: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion or type parameter conversion from 'U' to 'System.Enum'. // var b = new Test<U>(); // not enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "U").WithArguments("Test<T>", "System.Enum", "T", "U").WithLocation(14, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(15, 26), // (15,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.IDisposable'. // var c = new Test<int>(); // neither disposable nor enum Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.IDisposable", "T", "int").WithLocation(15, 26)); } [Fact] public void EnumConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Enum { } public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): 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 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Enum, new() { } public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26), // (15,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(15, 26), // (15,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(15, 26), // (16,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(16, 26)); } [Fact] public void EnumConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : class, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (11,26): error CS0452: The type 'E1' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<E1>(); // enum Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "E1").WithArguments("Test<T>", "T", "E1").WithLocation(11, 26), // (12,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26)); } [Fact] public void EnumConstraint_Reference_ValueType() { var reference = CreateCompilation(@" public class Test<T> where T : struct, System.Enum { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : struct, System.Enum { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): 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 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0453: The type 'Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Enum, new() { }" ).EmitToImageReference(); var code = @" public enum E1 { A } public class Test2 { public void M<U>() where U : System.Enum, new() { var a = new Test<E1>(); // enum var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<System.Enum>(); // Enum type var e = new Test<U>(); // Generic type constrained to enum } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (12,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(12, 26), // (13,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Enum'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Enum", "T", "string").WithLocation(13, 26), // (13,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (14,26): error CS0310: 'Enum' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var d = new Test<System.Enum>(); // Enum type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "System.Enum").WithArguments("Test<T>", "T", "System.Enum").WithLocation(14, 26)); } [Fact] public void EnumConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Enum { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'enum generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Enum").WithArguments("enum generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" enum E { } class Legacy { void M() { var a = new Test<E>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (10,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Enum'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Enum", "T", "Legacy").WithLocation(10, 26)); } [Theory] [InlineData("byte")] [InlineData("sbyte")] [InlineData("short")] [InlineData("ushort")] [InlineData("int")] [InlineData("uint")] [InlineData("long")] [InlineData("ulong")] public void EnumConstraint_DifferentBaseTypes(string type) { CreateCompilation($@" public class Test<T> where T : System.Enum {{ }} public enum E1 : {type} {{ A }} public class Test2 {{ public void M() {{ var a = new Test<E1>(); // Valid var b = new Test<int>(); // Invalid }} }} ").VerifyDiagnostics( // (14,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Enum'. // var b = new Test<int>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Enum", "T", "int").WithLocation(14, 26)); } [Fact] public void EnumConstraint_InheritanceChain() { CreateCompilation(@" public enum E { A } public class Test<T, U> where U : System.Enum, T { } public class Test2 { public void M() { var a = new Test<Test2, E>(); var b = new Test<E, E>(); var c = new Test<System.Enum, System.Enum>(); var d = new Test<E, System.Enum>(); var e = new Test<System.Enum, E>(); } }").VerifyDiagnostics( // (13,33): error CS0315: The type 'E' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no boxing conversion from 'E' to 'Test2'. // var a = new Test<Test2, E>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "E").WithArguments("Test<T, U>", "Test2", "U", "E").WithLocation(13, 33), // (18,29): error CS0311: The type 'System.Enum' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Enum' to 'E'. // var d = new Test<E, System.Enum>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Enum").WithArguments("Test<T, U>", "E", "U", "System.Enum").WithLocation(18, 29)); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ValueType() { var code = "public class Test<T> where T : struct, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Enum { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.True(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Enum, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Enum, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }").VerifyDiagnostics( // (12,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(12, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Enum; }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<E>(); } } public enum E { }", references: new[] { reference }).VerifyDiagnostics( // (8,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Enum'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Enum", "T", "int").WithLocation(8, 14) ); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Enum { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(8, 43)); } [Fact] public void EnumConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Enum { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Enum { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Enum").WithLocation(4, 43)); } [Fact] public void EnumConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public enum MyEnum { } public abstract class A<T> { public abstract void F<U>() where U : System.Enum, T; } public class B : A<MyEnum> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Enum", "MyEnum" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void EnumConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Enum { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Enum' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Enum Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Enum").WithArguments("Enum", "System").WithLocation(7, 39)); } [Fact] public void EnumConstraint_BindingToMethods() { var code = @" enum A : short { a } enum B : uint { b } class Test { public static void Main() { Print(A.a); Print(B.b); } static void Print<T>(T obj) where T : System.Enum { System.Console.WriteLine(obj.GetTypeCode()); } }"; CompileAndVerify(code, expectedOutput: @" Int16 UInt32"); } [Fact] public void EnumConstraint_InheritingFromEnum() { var code = @" public class Child : System.Enum { } public enum E { A } public class Test { public void M<T>(T arg) where T : System.Enum { } public void N() { M(E.A); // valid M(new Child()); // invalid } }"; CreateCompilation(code).VerifyDiagnostics( // (2,22): error CS0644: 'Child' cannot derive from special class 'Enum' // public class Child : System.Enum Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.Enum").WithArguments("Child", "System.Enum").WithLocation(2, 22), // (20,9): error CS0311: The type 'Child' cannot be used as type parameter 'T' in the generic type or method 'Test.M<T>(T)'. There is no implicit reference conversion from 'Child' to 'System.Enum'. // M(new Child()); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Test.M<T>(T)", "System.Enum", "T", "Child").WithLocation(20, 9)); } [Fact] public void DelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.Delegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.Delegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(2, 40) ); } [Fact] public void DelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void DelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.Delegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.Delegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.Delegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.Delegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.Delegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.Delegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.Delegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.Delegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.Delegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.Delegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.Delegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.Delegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void DelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.Delegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.Delegate, System.Delegate>(); var d = new Test<System.MulticastDelegate, System.Delegate>(); var e = new Test<System.Delegate, System.MulticastDelegate>(); var f = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var g = new Test<D1, System.Delegate>(); var h = new Test<System.Delegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (14,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var d = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(14, 52), // (18,30): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'D1'. // var g = new Test<D1, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "D1", "U", "System.Delegate").WithLocation(18, 30)); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.Delegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'Delegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.Delegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.Delegate").WithArguments("System.Delegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.Delegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.Delegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_Delegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.Delegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.Delegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.Delegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.Delegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(8, 43)); } [Fact] public void DelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.Delegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.Delegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.Delegate").WithLocation(4, 43)); } [Fact] public void DelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.Delegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.Delegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void DelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.Delegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'Delegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.Delegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Delegate").WithArguments("Delegate", "System").WithLocation(7, 39)); } [Fact] public void DelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.Delegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void MulticastDelegateConstraint_Compilation_Alone() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ReferenceType() { CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { } public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (11,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Compilation_ValueType() { CreateCompilation(@" public class Test<T> where T : struct, System.MulticastDelegate { }").VerifyDiagnostics( // (2,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(2, 40) ); } [Fact] public void MulticastDelegateConstraint_Compilation_Constructor() { CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { } public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }").VerifyDiagnostics( // (10,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(10, 26), // (11,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(11, 26), // (12,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(12, 26), // (12,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(12, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Alone() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_ReferenceType() { var reference = CreateCompilation(@" public class Test<T> where T : class, System.MulticastDelegate { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : class, System.MulticastDelegate { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (8,26): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("Test<T>", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Reference_Constructor() { var reference = CreateCompilation(@" public class Test<T> where T : System.MulticastDelegate, new() { }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class Test2 { public void M<U>() where U : System.MulticastDelegate, new() { var a = new Test<D1>(); // delegate var b = new Test<int>(); // value type var c = new Test<string>(); // reference type var d = new Test<U>(); // multicast delegate type } }", references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS0310: 'D1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var a = new Test<D1>(); // delegate Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "D1").WithArguments("Test<T>", "T", "D1").WithLocation(7, 26), // (8,26): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // var b = new Test<int>(); // value type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "int").WithArguments("Test<T>", "System.MulticastDelegate", "T", "int").WithLocation(8, 26), // (9,26): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'string' to 'System.MulticastDelegate'. // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "string").WithArguments("Test<T>", "System.MulticastDelegate", "T", "string").WithLocation(9, 26), // (9,26): error CS0310: 'string' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_NewConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_Before_7_3() { var code = @" public class Test<T> where T : System.MulticastDelegate { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'delegate generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "System.MulticastDelegate").WithArguments("delegate generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" delegate void D(); class Legacy { void M() { var a = new Test<D>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS0311: The type 'Legacy' cannot be used as type parameter 'T' in the generic type or method 'Test<T>'. There is no implicit reference conversion from 'Legacy' to 'System.MulticastDelegate'. // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "Legacy").WithArguments("Test<T>", "System.MulticastDelegate", "T", "Legacy").WithLocation(9, 26)); } [Fact] public void MulticastDelegateConstraint_InheritanceChain() { CreateCompilation(@" public delegate void D1(); public class Test<T, U> where U : System.MulticastDelegate, T { } public class Test2 { public void M() { var a = new Test<Test2, D1>(); var b = new Test<D1, D1>(); var c = new Test<System.MulticastDelegate, System.MulticastDelegate>(); var d = new Test<System.Delegate, System.MulticastDelegate>(); var e = new Test<System.MulticastDelegate, System.Delegate>(); var f = new Test<System.Delegate, System.Delegate>(); var g = new Test<D1, System.MulticastDelegate>(); var h = new Test<System.MulticastDelegate, D1>(); } }").VerifyDiagnostics( // (10,33): error CS0311: The type 'D1' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'D1' to 'Test2'. // var a = new Test<Test2, D1>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "D1").WithArguments("Test<T, U>", "Test2", "U", "D1").WithLocation(10, 33), // (15,52): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var e = new Test<System.MulticastDelegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(15, 52), // (16,43): error CS0311: The type 'System.Delegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.Delegate' to 'System.MulticastDelegate'. // var f = new Test<System.Delegate, System.Delegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.Delegate").WithArguments("Test<T, U>", "System.MulticastDelegate", "U", "System.Delegate").WithLocation(16, 43), // (18,30): error CS0311: The type 'System.MulticastDelegate' cannot be used as type parameter 'U' in the generic type or method 'Test<T, U>'. There is no implicit reference conversion from 'System.MulticastDelegate' to 'D1'. // var g = new Test<D1, System.MulticastDelegate>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "System.MulticastDelegate").WithArguments("Test<T, U>", "D1", "U", "System.MulticastDelegate").WithLocation(18, 30)); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Alone() { var code = "public class Test<T> where T : System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ValueType() { var compilation = CreateCompilation("public class Test<T> where T : struct, System.MulticastDelegate { }") .VerifyDiagnostics( // (1,40): error CS0450: 'MulticastDelegate': cannot specify both a constraint class and the 'class' or 'struct' constraint // public class Test<T> where T : struct, System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "System.MulticastDelegate").WithArguments("System.MulticastDelegate").WithLocation(1, 40) ); var typeParameter = compilation.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_ReferenceType() { var code = "public class Test<T> where T : class, System.MulticastDelegate { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_IsReflectedInSymbols_Constructor() { var code = "public class Test<T> where T : System.MulticastDelegate, new() { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.True(typeParameter.HasConstructorConstraint); Assert.Equal(SpecialType.System_MulticastDelegate, typeParameter.ConstraintTypes().Single().SpecialType); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; } public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }").VerifyDiagnostics( // (13,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(13, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : System.MulticastDelegate; }").EmitToImageReference(); CreateCompilation(@" public delegate void D1(); public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<D1>(); } }", references: new[] { reference }).VerifyDiagnostics( // (9,14): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'B.M<T>()'. There is no boxing conversion from 'int' to 'System.MulticastDelegate'. // this.M<int>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "M<int>").WithArguments("B.M<T>()", "System.MulticastDelegate", "T", "int").WithLocation(9, 14) ); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(8, 43)); } [Fact] public void MulticastDelegateConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : System.MulticastDelegate { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : System.MulticastDelegate { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "System.MulticastDelegate").WithLocation(4, 43)); } [Fact] public void MulticastDelegateConstraint_ResolveParentConstraints() { var comp = CreateCompilation(@" public delegate void D1(); public abstract class A<T> { public abstract void F<U>() where U : System.MulticastDelegate, T; } public class B : A<D1> { public override void F<U>() { } }"); Action<ModuleSymbol> validator = module => { var method = module.GlobalNamespace.GetTypeMember("B").GetMethod("F"); var constraintTypeNames = method.TypeParameters.Single().ConstraintTypes().Select(type => type.ToTestDisplayString()); AssertEx.SetEqual(new[] { "System.MulticastDelegate", "D1" }, constraintTypeNames); }; CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void MulticastDelegateConstraint_TypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} } public class Test<T> where T : System.MulticastDelegate { }").VerifyDiagnostics( // (7,39): error CS0234: The type or namespace name 'MulticastDelegate' does not exist in the namespace 'System' (are you missing an assembly reference?) // public class Test<T> where T : System.MulticastDelegate Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MulticastDelegate").WithArguments("MulticastDelegate", "System").WithLocation(7, 39)); } [Fact] public void MulticastDelegateConstraint_BindingToMethods() { var code = @" delegate void D1(int a, int b); class TestClass { public static void Impl(int a, int b) { System.Console.WriteLine($""Got {a} and {b}""); } public static void Main() { Test<D1>(Impl); } public static void Test<T>(T obj) where T : System.MulticastDelegate { obj.DynamicInvoke(2, 3); obj.DynamicInvoke(7, 9); } }"; CompileAndVerify(code, expectedOutput: @" Got 2 and 3 Got 7 and 9"); } [Fact] public void ConversionInInheritanceChain_MulticastDelegate() { var code = @" class A<T> where T : System.Delegate { } class B<T> : A<T> where T : System.MulticastDelegate { }"; CreateCompilation(code).VerifyDiagnostics(); code = @" class A<T> where T : System.MulticastDelegate { } class B<T> : A<T> where T : System.Delegate { }"; CreateCompilation(code).VerifyDiagnostics( // (3,7): error CS0311: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. There is no implicit reference conversion from 'T' to 'System.MulticastDelegate'. // class B<T> : A<T> where T : System.Delegate { } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "B").WithArguments("A<T>", "System.MulticastDelegate", "T", "T").WithLocation(3, 7)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Type() { CreateCompilation(@" public class Test<T> where T : unmanaged { } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (12,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(12, 26), // (13,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(13, 26), // (16,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(16, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Method() { CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; } public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(13, 28), // (14,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(14, 28), // (17,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(17, 28) ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_Delegate() { CreateCompilation(@" public delegate void D<T>() where T : unmanaged; public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }").VerifyDiagnostics( // (8,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(8, 32), // (9,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(9, 31), // (12,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(12, 26)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_Compilation_Alone_LocalFunction() { CreateCompilation(@" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { void M<T>() where T : unmanaged { } M<GoodType>(); // unmanaged struct M<BadType>(); // managed struct M<string>(); // reference type M<int>(); // value type M<U>(); // generic type constrained to unmanaged M<W>(); // unconstrained generic type } }").VerifyDiagnostics( // (13,9): error CS8377: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("M<T>()", "T", "BadType").WithLocation(13, 9), // (14,9): error CS8377: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("M<T>()", "T", "string").WithLocation(14, 9), // (17,9): error CS8377: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'M<T>()' // M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("M<T>()", "T", "W").WithLocation(17, 9)); } [Fact] public void UnmanagedConstraint_Compilation_ReferenceType() { var c = CreateCompilation("public class Test<T> where T : class, unmanaged {}"); c.VerifyDiagnostics( // (1,39): error CS0449: The 'unmanaged' constraint cannot be combined with the 'class' constraint // public class Test<T> where T : class, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 39)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.False(typeParameter.HasValueTypeConstraint); Assert.True(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_ValueType() { var c = CreateCompilation("public class Test<T> where T : struct, unmanaged {}"); c.VerifyDiagnostics( // (1,40): error CS0449: The 'unmanaged' constraint cannot be combined with the 'struct' constraint // public class Test<T> where T : struct, unmanaged {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 40)); var typeParameter = c.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.False(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); } [Fact] public void UnmanagedConstraint_Compilation_Constructor() { CreateCompilation("public class Test<T> where T : unmanaged, new() {}").VerifyDiagnostics( // (1,43): error CS8379: The 'new()' constraint cannot be used with the 'unmanaged' constraint // public class Test<T> where T : unmanaged, new() {} Diagnostic(ErrorCode.ERR_NewBoundWithUnmanaged, "new").WithLocation(1, 43)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_Before() { CreateCompilation("public class Test<T> where T : unmanaged, System.Exception { }").VerifyDiagnostics( // (1,43): error CS8380: 'Exception': cannot specify both a constraint class and the 'unmanaged' constraint // public class Test<T> where T : unmanaged, System.Exception { } Diagnostic(ErrorCode.ERR_UnmanagedBoundWithClass, "System.Exception").WithArguments("System.Exception").WithLocation(1, 43) ); } [Fact] public void UnmanagedConstraint_Compilation_AnotherClass_After() { CreateCompilation("public class Test<T> where T : System.Exception, unmanaged { }").VerifyDiagnostics( // (1,50): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Exception, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 50)); } [Fact] public void UnmanagedConstraint_Compilation_OtherValidTypes_After() { CreateCompilation("public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { }").VerifyDiagnostics( // (1,65): error CS8376: The 'unmanaged' constraint must come before any other constraints // public class Test<T> where T : System.Enum, System.IDisposable, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 65)); } [Fact] public void UnmanagedConstraint_OtherValidTypes_Before() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); AssertEx.Equal(new string[] { "Enum", "IDisposable" }, typeParameter.ConstraintTypes().Select(type => type.Name)); }; CompileAndVerify( "public class Test<T> where T : unmanaged, System.Enum, System.IDisposable { }", sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_After() { CreateCompilation("public class Test<T, U> where T : U, unmanaged { }").VerifyDiagnostics( // (1,38): error CS8380: The 'unmanaged' constraint must come before any other constraints // public class Test<T, U> where T : U, unmanaged { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(1, 38)); } [Fact] public void UnmanagedConstraint_Compilation_AnotherParameter_Before() { CreateCompilation("public class Test<T, U> where T : unmanaged, U { }").VerifyDiagnostics(); CreateCompilation("public class Test<T, U> where U: class where T : unmanaged, U, System.IDisposable { }").VerifyDiagnostics(); } [Fact] public void UnmanagedConstraint_UnmanagedEnumNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class ValueType {} } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (8,32): error CS0518: Predefined type 'System.Runtime.InteropServices.UnmanagedType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.Runtime.InteropServices.UnmanagedType").WithLocation(8, 32)); } [Fact] public void UnmanagedConstraint_ValueTypeNotAvailable() { CreateEmptyCompilation(@" namespace System { public class Object {} public class Void {} public class Enum {} public class Int32 {} namespace Runtime { namespace InteropServices { public enum UnmanagedType {} } } } public class Test<T> where T : unmanaged { }").VerifyDiagnostics( // (16,32): error CS0518: Predefined type 'System.ValueType' is not defined or imported // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "unmanaged").WithArguments("System.ValueType").WithLocation(16, 32)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Type() { var reference = CreateCompilation(@" public class Test<T> where T : unmanaged { }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test<GoodType>(); // unmanaged struct var b = new Test<BadType>(); // managed struct var c = new Test<string>(); // reference type var d = new Test<int>(); // value type var e = new Test<U>(); // generic type constrained to unmanaged var f = new Test<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,26): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "BadType").WithArguments("Test<T>", "T", "BadType").WithLocation(9, 26), // (10,26): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var c = new Test<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "string").WithArguments("Test<T>", "T", "string").WithLocation(10, 26), // (13,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var f = new Test<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "W").WithArguments("Test<T>", "T", "W").WithLocation(13, 26)); } [Fact] public void UnmanagedConstraint_Reference_Alone_Method() { var reference = CreateCompilation(@" public class Test { public int M<T>() where T : unmanaged => 0; }").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public class Test2 { public void M<U, W>() where U : unmanaged { var a = new Test().M<GoodType>(); // unmanaged struct var b = new Test().M<BadType>(); // managed struct var c = new Test().M<string>(); // reference type var d = new Test().M<int>(); // value type var e = new Test().M<U>(); // generic type constrained to unmanaged var f = new Test().M<W>(); // unconstrained generic type } }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (9,28): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var b = new Test().M<BadType>(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<BadType>").WithArguments("Test.M<T>()", "T", "BadType").WithLocation(9, 28), // (10,28): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var c = new Test().M<string>(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("Test.M<T>()", "T", "string").WithLocation(10, 28), // (13,28): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>()' // var f = new Test().M<W>(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<W>").WithArguments("Test.M<T>()", "T", "W").WithLocation(13, 28) ); } [Fact] public void UnmanagedConstraint_Reference_Alone_Delegate() { var reference = CreateCompilation(@" public delegate void D<T>() where T : unmanaged; ").EmitToImageReference(); var code = @" public struct GoodType { public int I; } public struct BadType { public string S; } public abstract class Test2<U, W> where U : unmanaged { public abstract D<GoodType> a(); // unmanaged struct public abstract D<BadType> b(); // managed struct public abstract D<string> c(); // reference type public abstract D<int> d(); // value type public abstract D<U> e(); // generic type constrained to unmanaged public abstract D<W> f(); // unconstrained generic type }"; CreateCompilation(code, references: new[] { reference }).VerifyDiagnostics( // (7,32): error CS8379: The type 'BadType' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<BadType> b(); // managed struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "b").WithArguments("D<T>", "T", "BadType").WithLocation(7, 32), // (8,31): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<string> c(); // reference type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "c").WithArguments("D<T>", "T", "string").WithLocation(8, 31), // (11,26): error CS8379: The type 'W' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'D<T>' // public abstract D<W> f(); // unconstrained generic type Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "f").WithArguments("D<T>", "T", "W").WithLocation(11, 26)); } [Fact] public void UnmanagedConstraint_Before_7_3() { var code = @" public class Test<T> where T : unmanaged { }"; var oldOptions = new CSharpParseOptions(LanguageVersion.CSharp7_2); CreateCompilation(code, parseOptions: oldOptions).VerifyDiagnostics( // (2,32): error CS8320: Feature 'unmanaged generic type constraints' is not available in C# 7.2. Please use language version 7.3 or greater. // public class Test<T> where T : unmanaged Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "unmanaged").WithArguments("unmanaged generic type constraints", "7.3").WithLocation(2, 32)); var reference = CreateCompilation(code).EmitToImageReference(); var legacyCode = @" class Legacy { void M() { var a = new Test<int>(); // valid var b = new Test<Legacy>(); // invalid } }"; CreateCompilation(legacyCode, parseOptions: oldOptions, references: new[] { reference }).VerifyDiagnostics( // (7,26): error CS8377: The type 'Legacy' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test<T>' // var b = new Test<Legacy>(); // invalid Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Legacy").WithArguments("Test<T>", "T", "Legacy").WithLocation(7, 26)); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Type() { var code = "public class Test<T> where T : unmanaged { }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Method() { var code = @" public class Test { public void M<T>() where T : unmanaged {} }"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").GetMethod("M").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_Delegate() { var code = "public delegate void D<T>() where T : unmanaged;"; Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("D").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }; CompileAndVerify(code, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void UnmanagedConstraint_IsReflectedInSymbols_Alone_LocalFunction() { var code = @" public class Test { public void M() { void N<T>() where T : unmanaged { } } }"; CompileAndVerify(code, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { var typeParameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__N|0_0").TypeParameters.Single(); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Empty(typeParameter.ConstraintTypes()); }); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Source() { CreateCompilation(@" struct Test { public string RefMember { get; set; } } public abstract class A { public abstract void M<T>() where T : unmanaged; } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }").VerifyDiagnostics( // (17,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(17, 14), // (18,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(18, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Downwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>() where T : unmanaged; }").EmitToImageReference(); CreateCompilation(@" struct Test { public string RefMember { get; set; } } public class B : A { public override void M<T>() { } public void Test() { this.M<int>(); this.M<string>(); this.M<Test>(); } }", references: new[] { reference }).VerifyDiagnostics( // (13,14): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<string>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<string>").WithArguments("B.M<T>()", "T", "string").WithLocation(13, 14), // (14,14): error CS8379: The type 'Test' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'B.M<T>()' // this.M<Test>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<Test>").WithArguments("B.M<T>()", "T", "Test").WithLocation(14, 14) ); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Source() { CreateCompilation(@" public abstract class A { public abstract void M<T>(); } public class B : A { public override void M<T>() where T : unmanaged { } }").VerifyDiagnostics( // (8,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(8, 43)); } [Fact] public void UnmanagedConstraint_StructMismatchInImplements() { CreateCompilation(@" public struct Segment<T> { public T[] array; } public interface I1<in T> where T : unmanaged { void Test<G>(G x) where G : unmanaged; } public class C2<T> : I1<T> where T : struct { public void Test<G>(G x) where G : struct { I1<T> i = this; i.Test(default(Segment<int>)); } } ").VerifyDiagnostics( // (11,14): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // public class C2<T> : I1<T> where T : struct Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "C2").WithArguments("I1<T>", "T", "T").WithLocation(11, 14), // (13,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : struct Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(13, 17), // (15,12): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'I1<T>' // I1<T> i = this; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "T").WithArguments("I1<T>", "T", "T").WithLocation(15, 12), // (16,11): error CS8377: The type 'Segment<int>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)' // i.Test(default(Segment<int>)); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "Test").WithArguments("I1<T>.Test<G>(G)", "G", "Segment<int>").WithLocation(16, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplements() { CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } } ").VerifyDiagnostics( // (7,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(7, 14), // (9,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(9, 17), // (11,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(11, 12), // (13,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(13, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta() { var reference = CreateCompilation(@" public interface I1<in T> where T : unmanaged, System.IDisposable { void Test<G>(G x) where G : unmanaged, System.Enum; } ").EmitToImageReference(); CreateCompilation(@" public class C2<T> : I1<T> where T : unmanaged { public void Test<G>(G x) where G : unmanaged { I1<T> i = this; i.Test(default(System.AttributeTargets)); // <-- this one is OK i.Test(0); } }", references: new[] { reference }).VerifyDiagnostics( // (2,14): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // public class C2<T> : I1<T> where T : unmanaged Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "C2").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(2, 14), // (4,17): error CS0425: The constraints for type parameter 'G' of method 'C2<T>.Test<G>(G)' must match the constraints for type parameter 'G' of interface method 'I1<T>.Test<G>(G)'. Consider using an explicit interface implementation instead. // public void Test<G>(G x) where G : unmanaged Diagnostic(ErrorCode.ERR_ImplBadConstraints, "Test").WithArguments("G", "C2<T>.Test<G>(G)", "G", "I1<T>.Test<G>(G)").WithLocation(4, 17), // (6,12): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'I1<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IDisposable'. // I1<T> i = this; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "T").WithArguments("I1<T>", "System.IDisposable", "T", "T").WithLocation(6, 12), // (8,11): error CS0315: The type 'int' cannot be used as type parameter 'G' in the generic type or method 'I1<T>.Test<G>(G)'. There is no boxing conversion from 'int' to 'System.Enum'. // i.Test(0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "Test").WithArguments("I1<T>.Test<G>(G)", "System.Enum", "G", "int").WithLocation(8, 11) ); } [Fact] public void UnmanagedConstraint_TypeMismatchInImplementsMeta2() { var reference = CreateCompilation(@" public interface I1 { void Test<G>(ref G x) where G : unmanaged, System.IDisposable; } ").EmitToImageReference(); var reference1 = CreateCompilation(@" public class C1 : I1 { void I1.Test<G>(ref G x) { x.Dispose(); } }", references: new[] { reference }).EmitToImageReference(); ; CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } class Test { static void Main() { S local = default; I1 i = new C1(); i.Test(ref local); System.Console.WriteLine(local.a); } }", // NOTE: must pass verification (IDisposable constraint is copied over to the implementing method) options: TestOptions.UnsafeReleaseExe, references: new[] { reference, reference1 }, verify: Verification.Passes, expectedOutput: "123"); } [Fact] public void UnmanagedConstraint_EnforcedInInheritanceChain_Upwards_Reference() { var reference = CreateCompilation(@" public abstract class A { public abstract void M<T>(); }").EmitToImageReference(); CreateCompilation(@" public class B : A { public override void M<T>() where T : unmanaged { } }", references: new[] { reference }).VerifyDiagnostics( // (4,43): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T>() where T : unmanaged { } Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "unmanaged").WithLocation(4, 43)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerOperations_Invalid() { CreateCompilation(@" class Test { void M<T>(T arg) where T : unmanaged { } void N() { M(""test""); } }").VerifyDiagnostics( // (9,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(9, 9)); } [ConditionalTheory(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [InlineData("(sbyte)1", "System.SByte", 1)] [InlineData("(byte)1", "System.Byte", 1)] [InlineData("(short)1", "System.Int16", 2)] [InlineData("(ushort)1", "System.UInt16", 2)] [InlineData("(int)1", "System.Int32", 4)] [InlineData("(uint)1", "System.UInt32", 4)] [InlineData("(long)1", "System.Int64", 8)] [InlineData("(ulong)1", "System.UInt64", 8)] [InlineData("'a'", "System.Char", 2)] [InlineData("(float)1", "System.Single", 4)] [InlineData("(double)1", "System.Double", 8)] [InlineData("(decimal)1", "System.Decimal", 16)] [InlineData("false", "System.Boolean", 1)] [InlineData("E.A", "E", 4)] [InlineData("new S { a = 1, b = 2, c = 3 }", "S", 12)] public void UnmanagedConstraints_PointerOperations_SimpleTypes(string arg, string type, int size) { CompileAndVerify(@" enum E { A } struct S { public int a; public int b; public int c; } unsafe class Test { static T* M<T>(T arg) where T : unmanaged { T* ptr = &arg; System.Console.WriteLine(ptr->GetType()); // method access System.Console.WriteLine(sizeof(T)); // sizeof operator T* ar = stackalloc T [10]; return ar; } static void Main() { M(" + arg + @"); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: string.Join(Environment.NewLine, type, size)).VerifyIL("Test.M<T>", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: ldarga.s V_0 IL_0002: conv.u IL_0003: constrained. ""T"" IL_0009: callvirt ""System.Type object.GetType()"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: sizeof ""T"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: ldc.i4.s 10 IL_0020: conv.u IL_0021: sizeof ""T"" IL_0027: mul.ovf.un IL_0028: localloc IL_002a: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_InterfaceMethod() { CompileAndVerify(@" struct S : System.IDisposable { public int a; public void Dispose() { a += 123; } } unsafe class Test { static void M<T>(ref T arg) where T : unmanaged, System.IDisposable { arg.Dispose(); fixed(T* ptr = &arg) { ptr->Dispose(); } } static void Main() { S local = default; M(ref local); System.Console.WriteLine(local.a); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "246").VerifyIL("Test.M<T>", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (pinned T& V_0) IL_0000: ldarg.0 IL_0001: constrained. ""T"" IL_0007: callvirt ""void System.IDisposable.Dispose()"" IL_000c: ldarg.0 IL_000d: stloc.0 IL_000e: ldloc.0 IL_000f: conv.u IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ldc.i4.0 IL_001c: conv.u IL_001d: stloc.0 IL_001e: ret }"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CtorAndValueTypeAreEmitted() { CompileAndVerify(@" using System.Linq; class Program { public static void M<T>() where T: unmanaged { } static void Main(string[] args) { var typeParam = typeof(Program).GetMethod(""M"").GetGenericArguments().First(); System.Console.WriteLine(typeParam.GenericParameterAttributes); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "NotNullableValueTypeConstraint, DefaultConstructorConstraint"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Flat() { CompileAndVerify(@" struct TestData { public int A; public TestData(int a) { A = a; } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "4"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Nested() { CompileAndVerify(@" struct InnerTestData { public int B; public InnerTestData(int b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, int b) { A = a; B = new InnerTestData(b); } } unsafe class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { System.Console.WriteLine(sizeof(T)); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: "8"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedStructs_Error() { CreateCompilation(@" struct InnerTestData { public string B; public InnerTestData(string b) { B = b; } } struct TestData { public int A; public InnerTestData B; public TestData(int a, string b) { A = a; B = new InnerTestData(b); } } class Test { public static void Main() { N<TestData>(); } static void N<T>() where T : unmanaged { } }").VerifyDiagnostics( // (24,9): error CS8379: The type 'TestData' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.N<T>()' // N<TestData>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "N<TestData>").WithArguments("Test.N<T>()", "T", "TestData").WithLocation(24, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_InScope() { CompileAndVerify(@" class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } class Test { public static void Main() { M(new unmanaged()); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }", expectedOutput: "success"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_ExistingUnmanagedKeywordType_OutOfScope() { CreateCompilation(@" namespace hidden { class unmanaged { public void Print() { System.Console.WriteLine(""success""); } } } class Test { public static void Main() { M(""test""); } static void M<T>(T arg) where T : unmanaged { arg.Print(); } }").VerifyDiagnostics( // (16,9): error CS8379: The type 'string' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'Test.M<T>(T)' // M("test"); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M").WithArguments("Test.M<T>(T)", "T", "string").WithLocation(16, 9), // (20,13): error CS1061: 'T' does not contain a definition for 'Print' and no extension method 'Print' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.Print(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Print").WithArguments("T", "Print").WithLocation(20, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Methods() { CompileAndVerify(@" class Program { static void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } static void B<T>(T arg) where T : unmanaged { A(arg); } static void Main() { B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Types() { CompileAndVerify(@" class A<T> where T : struct { public void M(T arg) { System.Console.WriteLine(arg); } } class B<T> : A<T> where T : unmanaged { } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_Interfaces() { CompileAndVerify(@" interface A<T> where T : struct { void M(T arg); } class B<T> : A<T> where T : unmanaged { public void M(T arg) { System.Console.WriteLine(arg); } } class Program { static void Main() { new B<int>().M(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedIsValidForStructConstraint_LocalFunctions() { CompileAndVerify(@" class Program { static void Main() { void A<T>(T arg) where T : struct { System.Console.WriteLine(arg); } void B<T>(T arg) where T : unmanaged { A(arg); } B(5); } }", expectedOutput: "5"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerTypeSubstitution() { var compilation = CreateCompilation(@" unsafe public class Test { public T* M<T>() where T : unmanaged => throw null; public void N() { var result = M<int>(); } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: true); var value = ((VariableDeclaratorSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.VariableDeclarator)).Initializer.Value; Assert.Equal("M<int>()", value.ToFullString()); var symbol = (IMethodSymbol)model.GetSymbolInfo(value).Symbol; Assert.Equal("System.Int32*", symbol.ReturnType.ToTestDisplayString()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CannotConstraintToTypeParameterConstrainedByUnmanaged() { CreateCompilation(@" class Test<U> where U : unmanaged { void M<T>() where T : U { } }").VerifyDiagnostics( // (4,12): error CS8379: Type parameter 'U' has the 'unmanaged' constraint so 'U' cannot be used as a constraint for 'T' // void M<T>() where T : U Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "T").WithArguments("T", "U").WithLocation(4, 12)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_UnmanagedAsTypeConstraintName() { CreateCompilation(@" class Test<unmanaged> where unmanaged : System.IDisposable { void M<T>(T arg) where T : unmanaged { arg.Dispose(); arg.NonExistentMethod(); } }").VerifyDiagnostics( // (7,13): error CS1061: 'T' does not contain a definition for 'NonExistentMethod' and no extension method 'NonExistentMethod' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // arg.NonExistentMethod(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "NonExistentMethod").WithArguments("T", "NonExistentMethod").WithLocation(7, 13)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_CircularReferenceToUnmanagedTypeWillBindSuccessfully() { CreateCompilation(@" public unsafe class C<U> where U : unmanaged { public void M1<T>() where T : T* { } public void M2<T>() where T : U* { } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M2<T>() where T : U* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "U*").WithLocation(5, 35), // (4,35): error CS0706: Invalid constraint type. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // public void M1<T>() where T : T* { } Diagnostic(ErrorCode.ERR_BadConstraintType, "T*").WithLocation(4, 35)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_EnumWithUnmanaged() { Action<ModuleSymbol> validator = module => { var typeParameter = module.GlobalNamespace.GetTypeMember("Test").TypeParameters.Single(); Assert.True(typeParameter.HasUnmanagedTypeConstraint); Assert.True(typeParameter.HasValueTypeConstraint); Assert.False(typeParameter.HasReferenceTypeConstraint); Assert.False(typeParameter.HasConstructorConstraint); Assert.Equal("Enum", typeParameter.ConstraintTypes().Single().Name); Assert.True(typeParameter.IsValueType); Assert.False(typeParameter.IsReferenceType); }; CompileAndVerify( source: "public class Test<T> where T : unmanaged, System.Enum {}", sourceSymbolValidator: validator, symbolValidator: validator); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_NestedInGenericType() { var code = @" public class Wrapper<T> { public enum E { } public struct S { } } public class Test { void IsUnmanaged<T>() where T : unmanaged { } void IsEnum<T>() where T : System.Enum { } void IsStruct<T>() where T : struct { } void IsNew<T>() where T : new() { } void User() { IsUnmanaged<Wrapper<int>.E>(); IsEnum<Wrapper<int>.E>(); IsStruct<Wrapper<int>.E>(); IsNew<Wrapper<int>.E>(); IsUnmanaged<Wrapper<int>.S>(); IsEnum<Wrapper<int>.S>(); // Invalid IsStruct<Wrapper<int>.S>(); IsNew<Wrapper<int>.S>(); IsUnmanaged<Wrapper<string>.E>(); IsEnum<Wrapper<string>.E>(); IsStruct<Wrapper<string>.E>(); IsNew<Wrapper<string>.E>(); IsUnmanaged<Wrapper<string>.S>(); IsEnum<Wrapper<string>.S>(); // Invalid IsStruct<Wrapper<string>.S>(); IsNew<Wrapper<string>.S>(); } }"; CreateCompilation(code).VerifyDiagnostics( // (28,9): error CS0315: The type 'Wrapper<int>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<int>.S' to 'System.Enum'. // IsEnum<Wrapper<int>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<int>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<int>.S").WithLocation(28, 9), // (38,9): error CS0315: The type 'Wrapper<string>.S' cannot be used as type parameter 'T' in the generic type or method 'Test.IsEnum<T>()'. There is no boxing conversion from 'Wrapper<string>.S' to 'System.Enum'. // IsEnum<Wrapper<string>.S>(); // Invalid Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "IsEnum<Wrapper<string>.S>").WithArguments("Test.IsEnum<T>()", "System.Enum", "T", "Wrapper<string>.S").WithLocation(38, 9)); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraints_PointerInsideStruct() { CompileAndVerify(@" unsafe struct S { public int a; public int* b; public S(int a, int* b) { this.a = a; this.b = b; } } unsafe class Test { static T* M<T>() where T : unmanaged { System.Console.WriteLine(typeof(T).FullName); T* ar = null; return ar; } static void Main() { S* ar = M<S>(); } }", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: "S"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_LambdaTypeParameters() { CompileAndVerify(@" public delegate T D<T>() where T : unmanaged; public class Test<U1> where U1 : unmanaged { public static void Print<T>(D<T> lambda) where T : unmanaged { System.Console.WriteLine(lambda()); } public static void User1(U1 arg) { Print(() => arg); } public static void User2<U2>(U2 arg) where U2 : unmanaged { Print(() => arg); } } public class Program { public static void Main() { // Testing the constraint when the lambda type parameter is both coming from an enclosing type, or copied to the generated lambda class Test<int>.User1(1); Test<int>.User2(2); } }", expectedOutput: @" 1 2", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.True(module.ContainingAssembly.GetTypeByMetadataName("D`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").TypeParameters.Single().HasUnmanagedTypeConstraint); Assert.True(module.ContainingAssembly.GetTypeByMetadataName("Test`1").GetTypeMember("<>c__DisplayClass2_0").TypeParameters.Single().HasUnmanagedTypeConstraint); }); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] public void UnmanagedConstraint_IsConsideredDuringOverloadResolution() { CompileAndVerify(@" public class Program { static void Test<T>(T arg) where T : unmanaged { System.Console.WriteLine(""Unmanaged: "" + arg); } static void Test(object arg) { System.Console.WriteLine(""Object: "" + arg); } static void User<U>(U arg) where U : unmanaged { Test(1); // should pick up the first, as it is better than the second one (which requires a conversion) Test(""2""); // should pick up the second, as it is the only candidate Test(arg); // should pick up the first, as it is the only candidate } static void Main() { User(3); } }", expectedOutput: @" Unmanaged: 1 Object: 2 Unmanaged: 3"); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { var p = stackalloc T[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_CallFromADifferentMethod() { var compilation = CreateCompilation(@" class C { unsafe void M<T>(T* a) where T : unmanaged { } unsafe void N() { var p = stackalloc int[10]; M(p); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { M(null, b); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod); Assert.Equal(declaredMethod.TypeParameters.Single().GetPublicSymbol(), inferredMethod.TypeArguments.Single()); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_WithOtherArgs_CallFromADifferentMethod() { var compilation = CreateCompilation(@" unsafe class C { static void M<T>(T* a, T b) where T : unmanaged { } static void N() { M(null, 5); } }", options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var call = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var inferredMethod = (IMethodSymbol)model.GetSymbolInfo(call).Symbol; var declaredMethod = compilation.GlobalNamespace.GetTypeMember("C").GetMethod("M"); Assert.Equal(declaredMethod.GetPublicSymbol(), inferredMethod.ConstructedFrom()); Assert.Equal(SpecialType.System_Int32, inferredMethod.TypeArguments.Single().SpecialType); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10782")] [WorkItem(25654, "https://github.com/dotnet/roslyn/issues/25654")] public void UnmanagedConstraint_PointersTypeInference_Errors() { CreateCompilation(@" unsafe class C { void Unmanaged<T>(T* a) where T : unmanaged { } void UnmanagedWithInterface<T>(T* a) where T : unmanaged, System.IDisposable { } void Test() { int a = 0; Unmanaged(0); // fail (type inference) Unmanaged(a); // fail (type inference) Unmanaged(&a); // succeed (unmanaged type pointer) UnmanagedWithInterface(0); // fail (type inference) UnmanagedWithInterface(a); // fail (type inference) UnmanagedWithInterface(&a); // fail (does not match interface) } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (14,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(14, 9), // (15,9): error CS0411: The type arguments for method 'C.Unmanaged<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Unmanaged(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Unmanaged").WithArguments("C.Unmanaged<T>(T*)").WithLocation(15, 9), // (18,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(0); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(18, 9), // (19,9): error CS0411: The type arguments for method 'C.UnmanagedWithInterface<T>(T*)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // UnmanagedWithInterface(a); // fail (type inference) Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)").WithLocation(19, 9), // (20,9): error CS0315: The type 'int' cannot be used as type parameter 'T' in the generic type or method 'C.UnmanagedWithInterface<T>(T*)'. There is no boxing conversion from 'int' to 'System.IDisposable'. // UnmanagedWithInterface(&a); // fail (does not match interface) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "UnmanagedWithInterface").WithArguments("C.UnmanagedWithInterface<T>(T*)", "System.IDisposable", "T", "int").WithLocation(20, 9)); } [Fact] public void UnmanagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void ManagedGenericStructPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2<T>(MyStruct<T>* ms) where T : unmanaged { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12)); } [Fact] public void UnmanagedGenericConstraintStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M() { MyStruct<int> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<int>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct OuterStruct { public int x; public InnerStruct inner; } public struct InnerStruct { public int y; } public class C { public unsafe void M() { MyStruct<OuterStruct> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<OuterStruct>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); } [Fact] public void UnmanagedGenericConstraintNestedGenericStructPointer() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics(); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18), // (17,12): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M2(&myStruct); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&myStruct").WithArguments("unmanaged constructed types", "8.0").WithLocation(17, 12), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55), // (20,55): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public unsafe void M2(MyStruct<InnerStruct<int>>* ms) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(20, 55)); } [Fact] public void UnmanagedGenericStructMultipleConstraints() { // A diagnostic will only be produced for the first violated constraint. var code = @" public struct MyStruct<T> where T : unmanaged, System.IDisposable { public T field; } public struct InnerStruct<U> { public U value; } public class C { public unsafe void M() { MyStruct<InnerStruct<int>> myStruct = default; _ = myStruct; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (16,18): error CS0315: The type 'InnerStruct<int>' cannot be used as type parameter 'T' in the generic type or method 'MyStruct<T>'. There is no boxing conversion from 'InnerStruct<int>' to 'System.IDisposable'. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedValType, "InnerStruct<int>").WithArguments("MyStruct<T>", "System.IDisposable", "T", "InnerStruct<int>").WithLocation(16, 18) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (16,18): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // MyStruct<InnerStruct<int>> myStruct = default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "InnerStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(16, 18) ); } [Fact] public void UnmanagedGenericConstraintPartialConstructedStruct() { var code = @" public struct MyStruct<T> where T : unmanaged { public T field; } public class C { public unsafe void M<U>() { MyStruct<U> myStruct; M2<U>(&myStruct); } public unsafe void M2<V>(MyStruct<V>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (11,18): error CS8377: The type 'U' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // MyStruct<U> myStruct; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "U").WithArguments("MyStruct<T>", "T", "U").WithLocation(11, 18), // (12,15): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<U>') // M2<U>(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<U>").WithLocation(12, 15), // (15,43): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<V>') // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<V>").WithLocation(15, 43), // (15,43): error CS8377: The type 'V' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'MyStruct<T>' // public unsafe void M2<V>(MyStruct<V>* ms) { } Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "ms").WithArguments("MyStruct<T>", "T", "V").WithLocation(15, 43)); } [Fact] public void GenericStructManagedFieldPointer() { var code = @" public struct MyStruct<T> { public T field; } public class C { public unsafe void M() { MyStruct<string> myStruct; M2(&myStruct); } public unsafe void M2(MyStruct<string>* ms) { } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,12): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // M2(&myStruct); Diagnostic(ErrorCode.ERR_ManagedAddr, "&myStruct").WithArguments("MyStruct<string>").WithLocation(12, 12), // (15,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<string>') // public unsafe void M2(MyStruct<string>* ms) { } Diagnostic(ErrorCode.ERR_ManagedAddr, "ms").WithArguments("MyStruct<string>").WithLocation(15, 45)); } [Fact] public void UnmanagedRecursiveGenericStruct() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public YourStruct<T>* field; } public unsafe struct YourStruct<T> where T : unmanaged { public MyStruct<T>* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveStruct() { var code = @" public unsafe struct MyStruct { public YourStruct* field; } public unsafe struct YourStruct { public MyStruct* field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgument() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedCyclic() { var code = @" public struct MyStruct<T> { public YourStruct<T> field; } public struct YourStruct<T> where T : unmanaged { public MyStruct<T> field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,26): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<T>' causes a cycle in the struct layout // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<T>").WithLocation(4, 26), // (4,26): error CS8377: The type 'T' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<T> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "T").WithLocation(4, 26), // (9,24): error CS0523: Struct member 'YourStruct<T>.field' of type 'MyStruct<T>' causes a cycle in the struct layout // public MyStruct<T> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("YourStruct<T>.field", "MyStruct<T>").WithLocation(9, 24)); Assert.False(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentManagedGenericField() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public T myField; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedExpandingTypeArgumentConstraintViolation() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; public string s; } public struct YourStruct<T> where T : unmanaged { public T field; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void UnmanagedRecursiveTypeArgumentConstraintViolation_02() { var code = @" public struct MyStruct<T> { public YourStruct<MyStruct<MyStruct<T>>> field; } public struct YourStruct<T> where T : unmanaged { public T field; public string s; } "; var compilation = CreateCompilation(code, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (4,46): error CS0523: Struct member 'MyStruct<T>.field' of type 'YourStruct<MyStruct<MyStruct<T>>>' causes a cycle in the struct layout // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "field").WithArguments("MyStruct<T>.field", "YourStruct<MyStruct<MyStruct<T>>>").WithLocation(4, 46), // (4,46): error CS8377: The type 'MyStruct<MyStruct<T>>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'YourStruct<T>' // public YourStruct<MyStruct<MyStruct<T>>> field; Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "field").WithArguments("YourStruct<T>", "T", "MyStruct<MyStruct<T>>").WithLocation(4, 46)); Assert.True(compilation.GetMember<NamedTypeSymbol>("MyStruct").IsManagedTypeNoUseSiteDiagnostics); Assert.True(compilation.GetMember<NamedTypeSymbol>("YourStruct").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void NestedGenericStructContainingPointer() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T* field; public T this[int index] { get { return field[index]; } } } public class C { public static unsafe void Main() { float f = 42; var ms = new MyStruct<float> { field = &f }; var test = new MyStruct<MyStruct<float>> { field = &ms }; float value = test[0][0]; System.Console.Write(value); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, expectedOutput: "42", verify: Verification.Skipped); } [Fact] public void SimpleGenericStructPointer_ILValidation() { var code = @" public unsafe struct MyStruct<T> where T : unmanaged { public T field; public static void Test() { var ms = new MyStruct<int>(); MyStruct<int>* ptr = &ms; ptr->field = 42; } } "; var il = @" { // Code size 19 (0x13) .maxstack 2 .locals init (MyStruct<int> V_0) //ms IL_0000: ldloca.s V_0 IL_0002: initobj ""MyStruct<int>"" IL_0008: ldloca.s V_0 IL_000a: conv.u IL_000b: ldc.i4.s 42 IL_000d: stfld ""int MyStruct<int>.field"" IL_0012: ret } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseDll, verify: Verification.Skipped) .VerifyIL("MyStruct<T>.Test", il); } [Fact, WorkItem(31439, "https://github.com/dotnet/roslyn/issues/31439")] public void CircularTypeArgumentUnmanagedConstraint() { var code = @" public struct X<T> where T : unmanaged { } public struct Z { public X<Z> field; }"; var compilation = CreateCompilation(code); compilation.VerifyDiagnostics(); Assert.False(compilation.GetMember<NamedTypeSymbol>("X").IsManagedTypeNoUseSiteDiagnostics); Assert.False(compilation.GetMember<NamedTypeSymbol>("Z").IsManagedTypeNoUseSiteDiagnostics); } [Fact] public void GenericStructAddressOfRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var ms = new MyStruct<int>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var ptr = &ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 19) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructFixedRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Test(MyClass c) { fixed (MyStruct<int>* ptr = &c.ms) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,16): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>*").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 16), // (12,37): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // fixed (MyStruct<int>* ptr = &c.ms) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "&c.ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 37)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructSizeofRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var size = sizeof(MyStruct<int>); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,20): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var size = sizeof(MyStruct<int>); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "sizeof(MyStruct<int>)").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 20) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericImplicitStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc[] { new MyStruct<int>() }; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,19): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc[] { new MyStruct<int>() }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc[] { new MyStruct<int>() }").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 19)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStackallocRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; public static unsafe void Test() { var arr = stackalloc MyStruct<int>[4]; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (8,30): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // var arr = stackalloc MyStruct<int>[4]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "MyStruct<int>").WithArguments("unmanaged constructed types", "8.0").WithLocation(8, 30)); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public T field; } public unsafe struct OtherStruct { public MyStruct<int>* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,27): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(9, 27) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void GenericNestedStructPointerFieldRequiresCSharp8() { var code = @" public struct MyStruct<T> { public struct InnerStruct { public T field; } } public unsafe struct OtherStruct { public MyStruct<int>.InnerStruct* ms; } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (12,39): error CS8370: Feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // public MyStruct<int>.InnerStruct* ms; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "ms").WithArguments("unmanaged constructed types", "8.0").WithLocation(12, 39) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingTuple_Unmanaged_RequiresCSharp8() { var code = @" public struct MyStruct { public (int, int) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2() { M<MyStruct>(); M<(int, int)>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (14,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<(int, int)>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<(int, int)>").WithArguments("unmanaged constructed types", "8.0").WithLocation(14, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(32103, "https://github.com/dotnet/roslyn/issues/32103")] public void StructContainingGenericTuple_Unmanaged() { var code = @" public struct MyStruct<T> { public (T, T) field; } public class C { public unsafe void M<T>() where T : unmanaged { } public void M2<U>() where U : unmanaged { M<MyStruct<U>>(); } public void M3<V>() { M<MyStruct<V>>(); } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (13,9): error CS8652: The feature 'unmanaged constructed types' is not available in C# 7.3. Please use language version 8.0 or greater. // M<MyStruct<U>>(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "M<MyStruct<U>>").WithArguments("unmanaged constructed types", "8.0").WithLocation(13, 9), // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (18,9): error CS8377: The type 'MyStruct<V>' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'T' in the generic type or method 'C.M<T>()' // M<MyStruct<V>>(); Diagnostic(ErrorCode.ERR_UnmanagedConstraintNotSatisfied, "M<MyStruct<V>>").WithArguments("C.M<T>()", "T", "MyStruct<V>").WithLocation(18, 9) ); } [Fact] public void GenericRefStructAddressOf_01() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>() { field = 42 }; var ptr = &ms; System.Console.Write(ptr->field); } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericRefStructAddressOf_02() { var code = @" public ref struct MyStruct<T> { public T field; } public class MyClass { public unsafe void M() { var ms = new MyStruct<object>(); var ptr = &ms; } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (12,19): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('MyStruct<object>') // var ptr = &ms; Diagnostic(ErrorCode.ERR_ManagedAddr, "&ms").WithArguments("MyStruct<object>").WithLocation(12, 19) ); } [Fact] public void GenericStructFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public MyStruct<int> ms; public static unsafe void Main() { var c = new MyClass(); c.ms.field = 42; fixed (MyStruct<int>* ptr = &c.ms) { System.Console.Write(ptr->field); } } } "; CompileAndVerify(code, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput: "42"); } [Fact] public void GenericStructLocalFixedStatement() { var code = @" public struct MyStruct<T> { public T field; } public class MyClass { public static unsafe void Main() { var ms = new MyStruct<int>(); fixed (int* ptr = &ms.field) { } } } "; CreateCompilation(code, options: TestOptions.UnsafeReleaseDll) .VerifyDiagnostics( // (12,27): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int* ptr = &ms.field) Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&ms.field").WithLocation(12, 27) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics() { var comp = CreateCompilation(@" class C1<T1> where T1 : class, struct, unmanaged, notnull { void M1<T2>() where T2 : class, struct, unmanaged, notnull {} } class C2<T1> where T1 : struct, class, unmanaged, notnull { void M2<T2>() where T2 : struct, class, unmanaged, notnull {} } class C3<T1> where T1 : class, class { void M3<T2>() where T2 : class, class {} } "); comp.VerifyDiagnostics( // (2,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(2, 32), // (2,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(2, 40), // (2,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C1<T1> where T1 : class, struct, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(2, 51), // (4,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(4, 37), // (4,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(4, 45), // (4,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M1<T2>() where T2 : class, struct, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 56), // (6,33): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(6, 33), // (6,40): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(6, 40), // (6,51): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C2<T1> where T1 : struct, class, unmanaged, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(6, 51), // (8,38): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 38), // (8,45): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "unmanaged").WithLocation(8, 45), // (8,56): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M2<T2>() where T2 : struct, class, unmanaged, notnull {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(8, 56), // (10,32): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // class C3<T1> where T1 : class, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(10, 32), // (12,37): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // void M3<T2>() where T2 : class, class {} Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(12, 37) ); } [Fact, WorkItem(45141, "https://github.com/dotnet/roslyn/issues/45141")] public void CannotCombineDiagnostics_InheritedClassStruct() { var comp = CreateCompilation(@" class C { public virtual void M<T1>() where T1 : class {} } class D : C { public override void M<T1>() where T1 : C, class, struct {} } class E { public virtual void M<T2>() where T2 : struct {} } class F : E { public override void M<T2>() where T2 : E, struct, class {} } class G { public virtual void M<T3>() where T3 : unmanaged {} } class H : G { public override void M<T3>() where T3 : G, unmanaged, struct {} } "); comp.VerifyDiagnostics( // (8,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T1>() where T1 : C, class, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "C").WithLocation(8, 45), // (16,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T2>() where T2 : E, struct, class {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "E").WithLocation(16, 45), // (24,45): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // public override void M<T3>() where T3 : G, unmanaged, struct {} Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "G").WithLocation(24, 45) ); } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Analyzers/Core/Analyzers/UseSystemHashCode/Analyzer.OperationDeconstructor.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseSystemHashCode { internal partial struct Analyzer { /// <summary> /// Breaks down complex <see cref="IOperation"/> trees, looking for particular /// <see cref="object.GetHashCode"/> patterns and extracting out the field and property /// symbols use to compute the hash. /// </summary> private struct OperationDeconstructor : IDisposable { private readonly Analyzer _analyzer; private readonly IMethodSymbol _method; private readonly ILocalSymbol? _hashCodeVariable; private readonly ArrayBuilder<ISymbol> _hashedSymbols; private bool _accessesBase; public OperationDeconstructor( Analyzer analyzer, IMethodSymbol method, ILocalSymbol? hashCodeVariable) { _analyzer = analyzer; _method = method; _hashCodeVariable = hashCodeVariable; _hashedSymbols = ArrayBuilder<ISymbol>.GetInstance(); _accessesBase = false; } public void Dispose() => _hashedSymbols.Free(); public (bool accessesBase, ImmutableArray<ISymbol> hashedSymbol) GetResult() => (_accessesBase, _hashedSymbols.ToImmutable()); /// <summary> /// Recursive function that decomposes <paramref name="value"/>, looking for particular /// forms that VS or ReSharper generate to hash fields in the containing type. /// </summary> /// <param name="seenHash">'seenHash' is used to determine if we actually saw something /// that indicates that we really hashed a field/property and weren't just simply /// referencing it. This is used as we recurse down to make sure we've seen a /// pattern we explicitly recognize by the time we hit a field/prop.</param> public bool TryAddHashedSymbol(IOperation value, bool seenHash) { value = Unwrap(value); switch (value) { case IBinaryOperation topBinary: // (hashCode op1 constant) op1 hashed_value // // This is generated by both VS and ReSharper. Though each use different mathematical // ops to combine the values. return _hashCodeVariable != null && topBinary.LeftOperand is IBinaryOperation leftBinary && IsLocalReference(leftBinary.LeftOperand, _hashCodeVariable) && IsLiteralNumber(leftBinary.RightOperand) && TryAddHashedSymbol(topBinary.RightOperand, seenHash: true); case IInvocationOperation invocation: var targetMethod = invocation.TargetMethod; if (_analyzer.OverridesSystemObject(targetMethod)) { // Either: // // a.GetHashCode() // // or // // (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() // // recurse on the value we're calling GetHashCode on. RoslynDebug.Assert(invocation.Instance is not null); return TryAddHashedSymbol(invocation.Instance, seenHash: true); } if (targetMethod.Name == nameof(GetHashCode) && Equals(_analyzer._equalityComparerType, targetMethod.ContainingType.OriginalDefinition) && invocation.Arguments.Length == 1) { // EqualityComparer<T>.Default.GetHashCode(i) // // VS codegen only. return TryAddHashedSymbol(invocation.Arguments[0].Value, seenHash: true); } // No other invocations supported. return false; case IConditionalOperation conditional: // (StringProperty != null ? StringProperty.GetHashCode() : 0) // // ReSharper codegen only. if (conditional.Condition is IBinaryOperation binary && Unwrap(binary.RightOperand).IsNullLiteral() && TryGetFieldOrProperty(binary.LeftOperand, out _)) { if (binary.OperatorKind == BinaryOperatorKind.Equals) { // (StringProperty == null ? 0 : StringProperty.GetHashCode()) RoslynDebug.Assert(conditional.WhenFalse is not null); return TryAddHashedSymbol(conditional.WhenFalse, seenHash: true); } else if (binary.OperatorKind == BinaryOperatorKind.NotEquals) { // (StringProperty != null ? StringProperty.GetHashCode() : 0) return TryAddHashedSymbol(conditional.WhenTrue, seenHash: true); } } // no other conditional forms supported. return false; } // Look to see if we're referencing some field/prop/base. However, we only accept // this reference if we've at least been through something that indicates that we've // hashed the value. if (seenHash) { if (value is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance && Equals(_method.ContainingType.BaseType, instanceReference.Type)) { if (_accessesBase) { // already had a reference to base.GetHashCode(); return false; } // reference to base. // // Happens with code like: `var hashCode = base.GetHashCode();` _accessesBase = true; return true; } // After decomposing all of the above patterns, we must end up with an operation that is // a reference to an instance-field (or prop) in our type. If so, and this is the only // time we've seen that field/prop, then we're good. // // We only do this if we actually did something that counts as hashing along the way. This // way if (TryGetFieldOrProperty(value, out var fieldOrProp) && Equals(fieldOrProp.ContainingType.OriginalDefinition, _method.ContainingType)) { return TryAddSymbol(fieldOrProp); } if (value is ITupleOperation tupleOperation) { foreach (var element in tupleOperation.Elements) { if (!TryAddHashedSymbol(element, seenHash: true)) { return false; } } return true; } } // Anything else is not recognized. return false; } private static bool TryGetFieldOrProperty(IOperation operation, [NotNullWhen(true)] out ISymbol? symbol) { operation = Unwrap(operation); if (operation is IFieldReferenceOperation fieldReference) { symbol = fieldReference.Member; return !symbol.IsStatic; } if (operation is IPropertyReferenceOperation propertyReference) { symbol = propertyReference.Member; return !symbol.IsStatic; } symbol = null; return false; } private bool TryAddSymbol(ISymbol member) { // Not a legal GetHashCode to convert if we refer to members multiple times. if (_hashedSymbols.Contains(member)) { return false; } _hashedSymbols.Add(member); 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.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseSystemHashCode { internal partial struct Analyzer { /// <summary> /// Breaks down complex <see cref="IOperation"/> trees, looking for particular /// <see cref="object.GetHashCode"/> patterns and extracting out the field and property /// symbols use to compute the hash. /// </summary> private struct OperationDeconstructor : IDisposable { private readonly Analyzer _analyzer; private readonly IMethodSymbol _method; private readonly ILocalSymbol? _hashCodeVariable; private readonly ArrayBuilder<ISymbol> _hashedSymbols; private bool _accessesBase; public OperationDeconstructor( Analyzer analyzer, IMethodSymbol method, ILocalSymbol? hashCodeVariable) { _analyzer = analyzer; _method = method; _hashCodeVariable = hashCodeVariable; _hashedSymbols = ArrayBuilder<ISymbol>.GetInstance(); _accessesBase = false; } public void Dispose() => _hashedSymbols.Free(); public (bool accessesBase, ImmutableArray<ISymbol> hashedSymbol) GetResult() => (_accessesBase, _hashedSymbols.ToImmutable()); /// <summary> /// Recursive function that decomposes <paramref name="value"/>, looking for particular /// forms that VS or ReSharper generate to hash fields in the containing type. /// </summary> /// <param name="seenHash">'seenHash' is used to determine if we actually saw something /// that indicates that we really hashed a field/property and weren't just simply /// referencing it. This is used as we recurse down to make sure we've seen a /// pattern we explicitly recognize by the time we hit a field/prop.</param> public bool TryAddHashedSymbol(IOperation value, bool seenHash) { value = Unwrap(value); switch (value) { case IBinaryOperation topBinary: // (hashCode op1 constant) op1 hashed_value // // This is generated by both VS and ReSharper. Though each use different mathematical // ops to combine the values. return _hashCodeVariable != null && topBinary.LeftOperand is IBinaryOperation leftBinary && IsLocalReference(leftBinary.LeftOperand, _hashCodeVariable) && IsLiteralNumber(leftBinary.RightOperand) && TryAddHashedSymbol(topBinary.RightOperand, seenHash: true); case IInvocationOperation invocation: var targetMethod = invocation.TargetMethod; if (_analyzer.OverridesSystemObject(targetMethod)) { // Either: // // a.GetHashCode() // // or // // (hashCode * -1521134295 + a.GetHashCode()).GetHashCode() // // recurse on the value we're calling GetHashCode on. RoslynDebug.Assert(invocation.Instance is not null); return TryAddHashedSymbol(invocation.Instance, seenHash: true); } if (targetMethod.Name == nameof(GetHashCode) && Equals(_analyzer._equalityComparerType, targetMethod.ContainingType.OriginalDefinition) && invocation.Arguments.Length == 1) { // EqualityComparer<T>.Default.GetHashCode(i) // // VS codegen only. return TryAddHashedSymbol(invocation.Arguments[0].Value, seenHash: true); } // No other invocations supported. return false; case IConditionalOperation conditional: // (StringProperty != null ? StringProperty.GetHashCode() : 0) // // ReSharper codegen only. if (conditional.Condition is IBinaryOperation binary && Unwrap(binary.RightOperand).IsNullLiteral() && TryGetFieldOrProperty(binary.LeftOperand, out _)) { if (binary.OperatorKind == BinaryOperatorKind.Equals) { // (StringProperty == null ? 0 : StringProperty.GetHashCode()) RoslynDebug.Assert(conditional.WhenFalse is not null); return TryAddHashedSymbol(conditional.WhenFalse, seenHash: true); } else if (binary.OperatorKind == BinaryOperatorKind.NotEquals) { // (StringProperty != null ? StringProperty.GetHashCode() : 0) return TryAddHashedSymbol(conditional.WhenTrue, seenHash: true); } } // no other conditional forms supported. return false; } // Look to see if we're referencing some field/prop/base. However, we only accept // this reference if we've at least been through something that indicates that we've // hashed the value. if (seenHash) { if (value is IInstanceReferenceOperation instanceReference && instanceReference.ReferenceKind == InstanceReferenceKind.ContainingTypeInstance && Equals(_method.ContainingType.BaseType, instanceReference.Type)) { if (_accessesBase) { // already had a reference to base.GetHashCode(); return false; } // reference to base. // // Happens with code like: `var hashCode = base.GetHashCode();` _accessesBase = true; return true; } // After decomposing all of the above patterns, we must end up with an operation that is // a reference to an instance-field (or prop) in our type. If so, and this is the only // time we've seen that field/prop, then we're good. // // We only do this if we actually did something that counts as hashing along the way. This // way if (TryGetFieldOrProperty(value, out var fieldOrProp) && Equals(fieldOrProp.ContainingType.OriginalDefinition, _method.ContainingType)) { return TryAddSymbol(fieldOrProp); } if (value is ITupleOperation tupleOperation) { foreach (var element in tupleOperation.Elements) { if (!TryAddHashedSymbol(element, seenHash: true)) { return false; } } return true; } } // Anything else is not recognized. return false; } private static bool TryGetFieldOrProperty(IOperation operation, [NotNullWhen(true)] out ISymbol? symbol) { operation = Unwrap(operation); if (operation is IFieldReferenceOperation fieldReference) { symbol = fieldReference.Member; return !symbol.IsStatic; } if (operation is IPropertyReferenceOperation propertyReference) { symbol = propertyReference.Member; return !symbol.IsStatic; } symbol = null; return false; } private bool TryAddSymbol(ISymbol member) { // Not a legal GetHashCode to convert if we refer to members multiple times. if (_hashedSymbols.Contains(member)) { return false; } _hashedSymbols.Add(member); return true; } } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialog.xaml
<vs:DialogWindow x:Uid="GenerateTypeDialog" AutomationProperties.AutomationId="GenerateTypeDialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType.GenerateTypeDialog" x:ClassModifier="internal" x:Name="dialog" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignWidth="460" Height="353" Width="460" MinHeight="370" MinWidth="460" Title="{Binding ElementName=dialog, Path=GenerateTypeDialogTitle}" HasHelpButton="True" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" HasDialogFrame="True" WindowStartupLocation="CenterOwner"> <StackPanel Margin="0,0,0,9" > <Label Content="{Binding ElementName=dialog, Path=TypeDetails}" FontWeight="Bold" Margin="20,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5"/> <Grid Margin="20,0,1,0" Height="49"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="105"/> <ColumnDefinition Width="Auto" MinWidth="99"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Label x:Name ="AccessLabel" Grid.Row="0" Grid.Column="0" Content="{Binding ElementName=dialog, Path=Access}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <Label x:Name ="KindLabel" Grid.Row="0" Grid.Column="1" Content="{Binding ElementName=dialog, Path=Kind}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <Label x:Name ="TypeNameLabel" Grid.Row="0" Grid.Column="2" Content="{Binding ElementName=dialog, Path=NameLabel}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <ComboBox x:Uid="AccessListUid" AutomationProperties.AutomationId="AccessList" AutomationProperties.LabeledBy="{Binding ElementName=AccessLabel}" Name="accessListComboBox" ItemsSource="{Binding AccessList}" SelectedIndex="{Binding AccessSelectIndex, Mode=Twoway}" SelectedItem="{Binding SelectedAccessibilityString, Mode=OneWayToSource}" IsEnabled="{Binding IsAccessListEnabled, Mode=TwoWay}" Grid.Row="1" Grid.Column="0" Margin="0,0,20,0"/> <ComboBox x:Uid="KindListUid" AutomationProperties.AutomationId="KindList" AutomationProperties.LabeledBy="{Binding ElementName=KindLabel}" Name="kindListComboBox" ItemsSource="{Binding KindList, Mode=TwoWay}" SelectedIndex="{Binding KindSelectIndex, Mode=Twoway}" SelectedItem="{Binding SelectedTypeKindString, Mode=OneWayToSource}" Grid.Row="1" Grid.Column="1" Margin="0,0,20,0"/> <TextBox x:Uid="TypeNameTextBoxUid" Name="TypeNameTextBox" AutomationProperties.AutomationId="TypeNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=TypeNameLabel}" Grid.Row="1" Grid.Column="2" IsReadOnly="True" HorizontalAlignment="Stretch" VerticalContentAlignment="Center" Padding="0,0,0,1" TextWrapping="Wrap" Text="{Binding TypeName}" Margin="0,0,20,0" Opacity="0.56"/> </Grid> <Separator Margin="10,10,10,0" HorizontalAlignment="Stretch"/> <Label x:Name="LocationLabel" Content="{Binding ElementName=dialog, Path=Location}" FontWeight="Bold" Margin="20,0,0,0"></Label> <StackPanel> <Label x:Name="ProjectLabel" Content="{Binding ElementName=dialog, Path=Project}" Margin="25,0,0,0"/> <ComboBox x:Uid="ProjectList" AutomationProperties.AutomationId="ProjectList" x:Name="projectListComboBox" AutomationProperties.LabeledBy="{Binding ElementName=ProjectLabel}" SelectedIndex="{Binding ProjectSelectIndex, Mode=Twoway}" ItemsSource="{Binding ProjectList, Mode=OneWay}" SelectedValue="{Binding SelectedProject}" SelectedValuePath="Project" DisplayMemberPath="Name" Margin="30,0,20,0" HorizontalAlignment="Stretch"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="AutomationProperties.Name" Value="{Binding Name}"/> </Style> </ComboBox.ItemContainerStyle> </ComboBox> </StackPanel> <StackPanel> <Label Content="{Binding ElementName=dialog, Path=FileName}" Margin="28,2,0,0"></Label> <RadioButton x:Uid="CreateNewFileRadioButton" AutomationProperties.AutomationId="CreateNewFileRadioButton" Content="{Binding ElementName=dialog, Path=CreateNewFile}" Margin="34,0,19,0" x:Name="createNewFileRadioButton" IsChecked="{Binding IsNewFile, Mode=TwoWay}"/> <ComboBox x:Uid="CreateNewFileComboBox" Name="CreateNewFileComboBox" AutomationProperties.AutomationId="CreateNewFileComboBox" Margin="48,1,20,0" IsEditable="True" Text="{Binding FileName, Mode=TwoWay}" ItemsSource="{Binding ProjectFolders, Mode=OneWay}" IsEnabled="{Binding ElementName=createNewFileRadioButton, Path=IsChecked}" HorizontalAlignment="Stretch" LostFocus="FileNameTextBox_LostFocus"> </ComboBox> <RadioButton x:Uid="AddToExistingFileRadioButton" AutomationProperties.AutomationId="AddToExistingFileRadioButton" Content="{Binding ElementName=dialog, Path=AddToExistingFile}" Margin="34,5,0,0" x:Name="addToExistingFileRadioButton" IsEnabled="{Binding IsExistingFileEnabled, Mode=TwoWay}" IsChecked="{Binding IsExistingFile, Mode=TwoWay}"/> <ComboBox x:Uid="AddToExistingFileComboBox" Name="AddToExistingFileComboBox" AutomationProperties.AutomationId="AddToExistingFileComboBox" SelectedIndex="{Binding DocumentSelectIndex, Mode=Twoway}" ItemsSource="{Binding DocumentList, Mode=OneWay}" DisplayMemberPath="Name" SelectedValue="{Binding SelectedDocument}" SelectedValuePath="Document" IsEditable="False" IsEnabled="{Binding IsChecked, ElementName=addToExistingFileRadioButton}" HorizontalAlignment="Stretch" Margin="48,1,20,0"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="AutomationProperties.Name" Value="{Binding Name}"/> </Style> </ComboBox.ItemContainerStyle> </ComboBox> </StackPanel> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Height="21" Width="147" Margin="0,15,21,0"> <Button x:Uid="OkButton" Name="OKButton" AutomationProperties.AutomationId="OkButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0,0,0,0" Click="OK_Click" IsDefault="True" MinHeight="20" MinWidth="70"/> <Button x:Uid="CancelButton" Name="CancelButton" AutomationProperties.AutomationId="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7,0,0,0" Click="Cancel_Click" IsCancel="True" MinHeight="20" MinWidth="70" RenderTransformOrigin="0.69,0.45"/> </StackPanel> </StackPanel> </vs:DialogWindow>
<vs:DialogWindow x:Uid="GenerateTypeDialog" AutomationProperties.AutomationId="GenerateTypeDialog" x:Class="Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType.GenerateTypeDialog" x:ClassModifier="internal" x:Name="dialog" xmlns:vs="clr-namespace:Microsoft.VisualStudio.PlatformUI;assembly=Microsoft.VisualStudio.Shell.15.0" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignWidth="460" Height="353" Width="460" MinHeight="370" MinWidth="460" Title="{Binding ElementName=dialog, Path=GenerateTypeDialogTitle}" HasHelpButton="True" ResizeMode="CanResizeWithGrip" ShowInTaskbar="False" HasDialogFrame="True" WindowStartupLocation="CenterOwner"> <StackPanel Margin="0,0,0,9" > <Label Content="{Binding ElementName=dialog, Path=TypeDetails}" FontWeight="Bold" Margin="20,10,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5"/> <Grid Margin="20,0,1,0" Height="49"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" MinWidth="105"/> <ColumnDefinition Width="Auto" MinWidth="99"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Label x:Name ="AccessLabel" Grid.Row="0" Grid.Column="0" Content="{Binding ElementName=dialog, Path=Access}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <Label x:Name ="KindLabel" Grid.Row="0" Grid.Column="1" Content="{Binding ElementName=dialog, Path=Kind}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <Label x:Name ="TypeNameLabel" Grid.Row="0" Grid.Column="2" Content="{Binding ElementName=dialog, Path=NameLabel}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="26"/> <ComboBox x:Uid="AccessListUid" AutomationProperties.AutomationId="AccessList" AutomationProperties.LabeledBy="{Binding ElementName=AccessLabel}" Name="accessListComboBox" ItemsSource="{Binding AccessList}" SelectedIndex="{Binding AccessSelectIndex, Mode=Twoway}" SelectedItem="{Binding SelectedAccessibilityString, Mode=OneWayToSource}" IsEnabled="{Binding IsAccessListEnabled, Mode=TwoWay}" Grid.Row="1" Grid.Column="0" Margin="0,0,20,0"/> <ComboBox x:Uid="KindListUid" AutomationProperties.AutomationId="KindList" AutomationProperties.LabeledBy="{Binding ElementName=KindLabel}" Name="kindListComboBox" ItemsSource="{Binding KindList, Mode=TwoWay}" SelectedIndex="{Binding KindSelectIndex, Mode=Twoway}" SelectedItem="{Binding SelectedTypeKindString, Mode=OneWayToSource}" Grid.Row="1" Grid.Column="1" Margin="0,0,20,0"/> <TextBox x:Uid="TypeNameTextBoxUid" Name="TypeNameTextBox" AutomationProperties.AutomationId="TypeNameTextBox" AutomationProperties.LabeledBy="{Binding ElementName=TypeNameLabel}" Grid.Row="1" Grid.Column="2" IsReadOnly="True" HorizontalAlignment="Stretch" VerticalContentAlignment="Center" Padding="0,0,0,1" TextWrapping="Wrap" Text="{Binding TypeName}" Margin="0,0,20,0" Opacity="0.56"/> </Grid> <Separator Margin="10,10,10,0" HorizontalAlignment="Stretch"/> <Label x:Name="LocationLabel" Content="{Binding ElementName=dialog, Path=Location}" FontWeight="Bold" Margin="20,0,0,0"></Label> <StackPanel> <Label x:Name="ProjectLabel" Content="{Binding ElementName=dialog, Path=Project}" Margin="25,0,0,0"/> <ComboBox x:Uid="ProjectList" AutomationProperties.AutomationId="ProjectList" x:Name="projectListComboBox" AutomationProperties.LabeledBy="{Binding ElementName=ProjectLabel}" SelectedIndex="{Binding ProjectSelectIndex, Mode=Twoway}" ItemsSource="{Binding ProjectList, Mode=OneWay}" SelectedValue="{Binding SelectedProject}" SelectedValuePath="Project" DisplayMemberPath="Name" Margin="30,0,20,0" HorizontalAlignment="Stretch"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="AutomationProperties.Name" Value="{Binding Name}"/> </Style> </ComboBox.ItemContainerStyle> </ComboBox> </StackPanel> <StackPanel> <Label Content="{Binding ElementName=dialog, Path=FileName}" Margin="28,2,0,0"></Label> <RadioButton x:Uid="CreateNewFileRadioButton" AutomationProperties.AutomationId="CreateNewFileRadioButton" Content="{Binding ElementName=dialog, Path=CreateNewFile}" Margin="34,0,19,0" x:Name="createNewFileRadioButton" IsChecked="{Binding IsNewFile, Mode=TwoWay}"/> <ComboBox x:Uid="CreateNewFileComboBox" Name="CreateNewFileComboBox" AutomationProperties.AutomationId="CreateNewFileComboBox" Margin="48,1,20,0" IsEditable="True" Text="{Binding FileName, Mode=TwoWay}" ItemsSource="{Binding ProjectFolders, Mode=OneWay}" IsEnabled="{Binding ElementName=createNewFileRadioButton, Path=IsChecked}" HorizontalAlignment="Stretch" LostFocus="FileNameTextBox_LostFocus"> </ComboBox> <RadioButton x:Uid="AddToExistingFileRadioButton" AutomationProperties.AutomationId="AddToExistingFileRadioButton" Content="{Binding ElementName=dialog, Path=AddToExistingFile}" Margin="34,5,0,0" x:Name="addToExistingFileRadioButton" IsEnabled="{Binding IsExistingFileEnabled, Mode=TwoWay}" IsChecked="{Binding IsExistingFile, Mode=TwoWay}"/> <ComboBox x:Uid="AddToExistingFileComboBox" Name="AddToExistingFileComboBox" AutomationProperties.AutomationId="AddToExistingFileComboBox" SelectedIndex="{Binding DocumentSelectIndex, Mode=Twoway}" ItemsSource="{Binding DocumentList, Mode=OneWay}" DisplayMemberPath="Name" SelectedValue="{Binding SelectedDocument}" SelectedValuePath="Document" IsEditable="False" IsEnabled="{Binding IsChecked, ElementName=addToExistingFileRadioButton}" HorizontalAlignment="Stretch" Margin="48,1,20,0"> <ComboBox.ItemContainerStyle> <Style TargetType="ComboBoxItem"> <Setter Property="AutomationProperties.Name" Value="{Binding Name}"/> </Style> </ComboBox.ItemContainerStyle> </ComboBox> </StackPanel> <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Height="21" Width="147" Margin="0,15,21,0"> <Button x:Uid="OkButton" Name="OKButton" AutomationProperties.AutomationId="OkButton" Content="{Binding ElementName=dialog, Path=OK}" Margin="0,0,0,0" Click="OK_Click" IsDefault="True" MinHeight="20" MinWidth="70"/> <Button x:Uid="CancelButton" Name="CancelButton" AutomationProperties.AutomationId="CancelButton" Content="{Binding ElementName=dialog, Path=Cancel}" Margin="7,0,0,0" Click="Cancel_Click" IsCancel="True" MinHeight="20" MinWidth="70" RenderTransformOrigin="0.69,0.45"/> </StackPanel> </StackPanel> </vs:DialogWindow>
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Extensions/IVsRunningDocumentTableExtensions.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.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class IVsRunningDocumentTableExtensions { public static bool IsDocumentInitialized(this IVsRunningDocumentTable4 runningDocTable, uint docCookie) { var flags = runningDocTable.GetDocumentFlags(docCookie); return (flags & (uint)_VSRDTFLAGS4.RDT_PendingInitialization) == 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. #nullable disable using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class IVsRunningDocumentTableExtensions { public static bool IsDocumentInitialized(this IVsRunningDocumentTable4 runningDocTable, uint docCookie) { var flags = runningDocTable.GetDocumentFlags(docCookie); return (flags & (uint)_VSRDTFLAGS4.RDT_PendingInitialization) == 0; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeEnumTests.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 EnvDTE Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEnumTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeEnum) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE.CodeEnum) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetBases(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Bases End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As CodeEnum) As vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeEnum) As Object Return codeElement.Parent End Function Protected Overrides Function AddEnumMember(codeElement As EnvDTE.CodeEnum, data As EnumMemberData) As EnvDTE.CodeVariable Return codeElement.AddMember(data.Name, data.Value, data.Position) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE.CodeEnum, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Sub RemoveChild(codeElement As CodeEnum, child As Object) codeElement.RemoveMember(child) End Sub Protected Overrides Function GetAccessSetter(codeElement As EnvDTE.CodeEnum) As Action(Of EnvDTE.vsCMAccess) Return Sub(access) codeElement.Access = access End Function Protected Overrides Function GetNameSetter(codeElement As CodeEnum) As Action(Of String) Return Sub(name) codeElement.Name = name 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 EnvDTE Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEnumTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeEnum) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE.CodeEnum) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetBases(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Bases End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As CodeEnum) As vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeEnum) As Object Return codeElement.Parent End Function Protected Overrides Function AddEnumMember(codeElement As EnvDTE.CodeEnum, data As EnumMemberData) As EnvDTE.CodeVariable Return codeElement.AddMember(data.Name, data.Value, data.Position) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE.CodeEnum, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Sub RemoveChild(codeElement As CodeEnum, child As Object) codeElement.RemoveMember(child) End Sub Protected Overrides Function GetAccessSetter(codeElement As EnvDTE.CodeEnum) As Action(Of EnvDTE.vsCMAccess) Return Sub(access) codeElement.Access = access End Function Protected Overrides Function GetNameSetter(codeElement As CodeEnum) As Action(Of String) Return Sub(name) codeElement.Name = name End Function End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/Core/DocumentSnapshotSpan.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.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { /// <summary> /// Represents an editor <see cref="VisualStudio.Text.SnapshotSpan"/> and the <see cref="CodeAnalysis.Document"/> /// the span was produced from. /// </summary> internal readonly struct DocumentSnapshotSpan { /// <summary> /// The <see cref="CodeAnalysis.Document"/> the span was produced from. /// </summary> public Document? Document { get; } /// <summary> /// The editor <see cref="VisualStudio.Text.SnapshotSpan"/>. /// </summary> public SnapshotSpan SnapshotSpan { get; } /// <summary> /// Creates a new <see cref="DocumentSnapshotSpan"/>. /// </summary> public DocumentSnapshotSpan(Document? document, SnapshotSpan snapshotSpan) { this.Document = document; this.SnapshotSpan = snapshotSpan; } } }
// 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.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor { /// <summary> /// Represents an editor <see cref="VisualStudio.Text.SnapshotSpan"/> and the <see cref="CodeAnalysis.Document"/> /// the span was produced from. /// </summary> internal readonly struct DocumentSnapshotSpan { /// <summary> /// The <see cref="CodeAnalysis.Document"/> the span was produced from. /// </summary> public Document? Document { get; } /// <summary> /// The editor <see cref="VisualStudio.Text.SnapshotSpan"/>. /// </summary> public SnapshotSpan SnapshotSpan { get; } /// <summary> /// Creates a new <see cref="DocumentSnapshotSpan"/>. /// </summary> public DocumentSnapshotSpan(Document? document, SnapshotSpan snapshotSpan) { this.Document = document; this.SnapshotSpan = snapshotSpan; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Workspaces/Remote/ServiceHub/Services/TodoCommentsDiscovery/RemoteTodoCommentsIncrementalAnalyzerProvider.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; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
// 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; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Server/VBCSCompiler/ClientConnectionHandler.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 System.IO; using System.IO.Pipes; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class is responsible for processing a request from a client of the compiler server. /// </summary> internal sealed class ClientConnectionHandler { internal ICompilerServerHost CompilerServerHost { get; } internal ICompilerServerLogger Logger => CompilerServerHost.Logger; internal ClientConnectionHandler(ICompilerServerHost compilerServerHost) { CompilerServerHost = compilerServerHost; } /// <summary> /// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped /// in a <see cref="CompletionReason.RequestError"/> /// </summary> internal async Task<CompletionData> ProcessAsync( Task<IClientConnection> clientConnectionTask, bool allowCompilationRequests = true, CancellationToken cancellationToken = default) { try { return await ProcessCore().ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error processing request for client"); return CompletionData.RequestError; } async Task<CompletionData> ProcessCore() { using var clientConnection = await clientConnectionTask.ConfigureAwait(false); var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false); Logger.Log($"Received request {request.RequestId} of type {request.GetType()}"); if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new IncorrectHashBuildResponse(), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new ShutdownBuildResponse(Process.GetCurrentProcess().Id), new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), cancellationToken).ConfigureAwait(false); } if (!allowCompilationRequests) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Compilation not allowed at this time"), CompletionData.RequestCompleted, cancellationToken).ConfigureAwait(false); } if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Not enough resources to accept connection"), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false); } } private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) { var message = response switch { RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}", _ => $"Writing {response.Type} response for {requestId}" }; Logger.Log(message); await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false); return completionData; } private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken) { // Need to wait for the compilation and client disconnection in parallel. If the client // suddenly disconnects we need to cancel the compilation that is occurring. It could be the // client hit Ctrl-C due to a run away analyzer. var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token); await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false); try { if (compilationTask.IsCompleted) { BuildResponse response; CompletionData completionData; try { response = await compilationTask.ConfigureAwait(false); completionData = response switch { // Once there is an analyzer inconsistency the assembly load space is polluted. The // request is an error. AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError, _ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request)) }; } catch (Exception ex) { // The compilation task should never throw. If it does we need to assume that the compiler is // in a bad state and need to issue a RequestError Logger.LogException(ex, $"Exception running compilation for {request.RequestId}"); response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}"); completionData = CompletionData.RequestError; } return await WriteBuildResponseAsync( clientConnection, request.RequestId, response, completionData, cancellationToken).ConfigureAwait(false); } else { return CompletionData.RequestError; } } finally { buildCancellationTokenSource.Cancel(); } static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken) { Func<BuildResponse> func = () => { var request = BuildProtocolUtil.GetRunRequest(buildRequest); var response = compilerServerHost.RunCompilation(request, cancellationToken); return response; }; var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning); task.Start(); return task; } } /// <summary> /// Check the request arguments for a new keep alive time. If one is present, /// set the server timer to the new time. /// </summary> private static TimeSpan? CheckForNewKeepAlive(BuildRequest request) { TimeSpan? timeout = null; foreach (var arg in request.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive) { int result; // If the value is not a valid integer for any reason, // ignore it and continue with the current timeout. The client // is responsible for validating the argument. if (int.TryParse(arg.Value, out result)) { // Keep alive times are specified in seconds timeout = TimeSpan.FromSeconds(result); } } } return timeout; } } }
// 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 System.IO; using System.IO.Pipes; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.CompilerServer { /// <summary> /// This class is responsible for processing a request from a client of the compiler server. /// </summary> internal sealed class ClientConnectionHandler { internal ICompilerServerHost CompilerServerHost { get; } internal ICompilerServerLogger Logger => CompilerServerHost.Logger; internal ClientConnectionHandler(ICompilerServerHost compilerServerHost) { CompilerServerHost = compilerServerHost; } /// <summary> /// Handles a client connection. The returned task here will never fail. Instead all exceptions will be wrapped /// in a <see cref="CompletionReason.RequestError"/> /// </summary> internal async Task<CompletionData> ProcessAsync( Task<IClientConnection> clientConnectionTask, bool allowCompilationRequests = true, CancellationToken cancellationToken = default) { try { return await ProcessCore().ConfigureAwait(false); } catch (Exception ex) { Logger.LogException(ex, $"Error processing request for client"); return CompletionData.RequestError; } async Task<CompletionData> ProcessCore() { using var clientConnection = await clientConnectionTask.ConfigureAwait(false); var request = await clientConnection.ReadBuildRequestAsync(cancellationToken).ConfigureAwait(false); Logger.Log($"Received request {request.RequestId} of type {request.GetType()}"); if (!string.Equals(request.CompilerHash, BuildProtocolConstants.GetCommitHash(), StringComparison.OrdinalIgnoreCase)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new IncorrectHashBuildResponse(), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } if (request.Arguments.Count == 1 && request.Arguments[0].ArgumentId == BuildProtocolConstants.ArgumentId.Shutdown) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new ShutdownBuildResponse(Process.GetCurrentProcess().Id), new CompletionData(CompletionReason.RequestCompleted, shutdownRequested: true), cancellationToken).ConfigureAwait(false); } if (!allowCompilationRequests) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Compilation not allowed at this time"), CompletionData.RequestCompleted, cancellationToken).ConfigureAwait(false); } if (!Environment.Is64BitProcess && !MemoryHelper.IsMemoryAvailable(Logger)) { return await WriteBuildResponseAsync( clientConnection, request.RequestId, new RejectedBuildResponse("Not enough resources to accept connection"), CompletionData.RequestError, cancellationToken).ConfigureAwait(false); } return await ProcessCompilationRequestAsync(clientConnection, request, cancellationToken).ConfigureAwait(false); } } private async Task<CompletionData> WriteBuildResponseAsync(IClientConnection clientConnection, Guid requestId, BuildResponse response, CompletionData completionData, CancellationToken cancellationToken) { var message = response switch { RejectedBuildResponse r => $"Writing {r.Type} response '{r.Reason}' for {requestId}", _ => $"Writing {response.Type} response for {requestId}" }; Logger.Log(message); await clientConnection.WriteBuildResponseAsync(response, cancellationToken).ConfigureAwait(false); return completionData; } private async Task<CompletionData> ProcessCompilationRequestAsync(IClientConnection clientConnection, BuildRequest request, CancellationToken cancellationToken) { // Need to wait for the compilation and client disconnection in parallel. If the client // suddenly disconnects we need to cancel the compilation that is occurring. It could be the // client hit Ctrl-C due to a run away analyzer. var buildCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var compilationTask = ProcessCompilationRequestCore(CompilerServerHost, request, buildCancellationTokenSource.Token); await Task.WhenAny(compilationTask, clientConnection.DisconnectTask).ConfigureAwait(false); try { if (compilationTask.IsCompleted) { BuildResponse response; CompletionData completionData; try { response = await compilationTask.ConfigureAwait(false); completionData = response switch { // Once there is an analyzer inconsistency the assembly load space is polluted. The // request is an error. AnalyzerInconsistencyBuildResponse _ => CompletionData.RequestError, _ => new CompletionData(CompletionReason.RequestCompleted, newKeepAlive: CheckForNewKeepAlive(request)) }; } catch (Exception ex) { // The compilation task should never throw. If it does we need to assume that the compiler is // in a bad state and need to issue a RequestError Logger.LogException(ex, $"Exception running compilation for {request.RequestId}"); response = new RejectedBuildResponse($"Exception during compilation: {ex.Message}"); completionData = CompletionData.RequestError; } return await WriteBuildResponseAsync( clientConnection, request.RequestId, response, completionData, cancellationToken).ConfigureAwait(false); } else { return CompletionData.RequestError; } } finally { buildCancellationTokenSource.Cancel(); } static Task<BuildResponse> ProcessCompilationRequestCore(ICompilerServerHost compilerServerHost, BuildRequest buildRequest, CancellationToken cancellationToken) { Func<BuildResponse> func = () => { var request = BuildProtocolUtil.GetRunRequest(buildRequest); var response = compilerServerHost.RunCompilation(request, cancellationToken); return response; }; var task = new Task<BuildResponse>(func, cancellationToken, TaskCreationOptions.LongRunning); task.Start(); return task; } } /// <summary> /// Check the request arguments for a new keep alive time. If one is present, /// set the server timer to the new time. /// </summary> private static TimeSpan? CheckForNewKeepAlive(BuildRequest request) { TimeSpan? timeout = null; foreach (var arg in request.Arguments) { if (arg.ArgumentId == BuildProtocolConstants.ArgumentId.KeepAlive) { int result; // If the value is not a valid integer for any reason, // ignore it and continue with the current timeout. The client // is responsible for validating the argument. if (int.TryParse(arg.Value, out result)) { // Keep alive times are specified in seconds timeout = TimeSpan.FromSeconds(result); } } } return timeout; } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/AlwaysAssignedWalker.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that computes the set of variables that are always assigned a value in the region. ''' A variable is "always assigned" in a region if an analysis of the ''' region that starts with the variable unassigned ends with the variable ''' assigned. ''' </summary> Friend Class AlwaysAssignedWalker Inherits AbstractRegionDataFlowPass Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) As IEnumerable(Of Symbol) Dim walker = New AlwaysAssignedWalker(info, region) Try Dim result As Boolean = walker.Analyze() Return If(result, walker.AlwaysAssigned, SpecializedCollections.EmptyEnumerable(Of Symbol)()) Finally walker.Free() End Try End Function Private _endOfRegionState As LocalState Private ReadOnly _labelsInside As New HashSet(Of LabelSymbol)() Private ReadOnly Property AlwaysAssigned As IEnumerable(Of Symbol) Get Dim result As New List(Of Symbol) If (_endOfRegionState.Reachable) Then For Each i In _endOfRegionState.Assigned.TrueBits If (i >= variableBySlot.Length) Then Continue For End If Dim v = variableBySlot(i) If v.Exists AndAlso v.Symbol.Kind <> SymbolKind.Field Then result.Add(v.Symbol) End If Next End If Return result End Get End Property Protected Overrides Sub EnterRegion() MyBase.SetState(ReachableState()) MyBase.EnterRegion() End Sub Protected Overrides Sub LeaveRegion() If Me.IsConditionalState Then ' If the region is in a condition, then the state will be split and ' State.Assigned(will) be null. Merge to get sensible results. _endOfRegionState = Me.StateWhenTrue.Clone() IntersectWith(_endOfRegionState, Me.StateWhenFalse) Else _endOfRegionState = MyBase.State.Clone() End If Debug.Assert(Not _endOfRegionState.Assigned.IsNull) For Each branch In PendingBranches If IsInsideRegion(branch.Branch.Syntax.Span) AndAlso Not _labelsInside.Contains(branch.Label) Then IntersectWith(_endOfRegionState, branch.State) End If Next MyBase.LeaveRegion() End Sub Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode If node.Syntax IsNot Nothing AndAlso IsInsideRegion(node.Syntax.Span) Then _labelsInside.Add(node.Label) End If Return MyBase.VisitLabelStatement(node) End Function Protected Overrides Sub ResolveBranch(pending As AbstractFlowPass(Of DataFlowPass.LocalState).PendingBranch, label As LabelSymbol, target As BoundLabelStatement, ByRef labelStateChanged As Boolean) If IsInside AndAlso pending.Branch IsNot Nothing AndAlso Not IsInsideRegion(pending.Branch.Syntax.Span) Then pending.State = If(pending.State.Reachable, ReachableState(), UnreachableState()) End If MyBase.ResolveBranch(pending, label, target, labelStateChanged) End Sub Protected Overrides Sub WriteArgument(arg As BoundExpression, isOut As Boolean) ' ref parameter must be '<Out()>' to "always" assign If isOut Then MyBase.WriteArgument(arg, isOut) 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.Collections.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that computes the set of variables that are always assigned a value in the region. ''' A variable is "always assigned" in a region if an analysis of the ''' region that starts with the variable unassigned ends with the variable ''' assigned. ''' </summary> Friend Class AlwaysAssignedWalker Inherits AbstractRegionDataFlowPass Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) As IEnumerable(Of Symbol) Dim walker = New AlwaysAssignedWalker(info, region) Try Dim result As Boolean = walker.Analyze() Return If(result, walker.AlwaysAssigned, SpecializedCollections.EmptyEnumerable(Of Symbol)()) Finally walker.Free() End Try End Function Private _endOfRegionState As LocalState Private ReadOnly _labelsInside As New HashSet(Of LabelSymbol)() Private ReadOnly Property AlwaysAssigned As IEnumerable(Of Symbol) Get Dim result As New List(Of Symbol) If (_endOfRegionState.Reachable) Then For Each i In _endOfRegionState.Assigned.TrueBits If (i >= variableBySlot.Length) Then Continue For End If Dim v = variableBySlot(i) If v.Exists AndAlso v.Symbol.Kind <> SymbolKind.Field Then result.Add(v.Symbol) End If Next End If Return result End Get End Property Protected Overrides Sub EnterRegion() MyBase.SetState(ReachableState()) MyBase.EnterRegion() End Sub Protected Overrides Sub LeaveRegion() If Me.IsConditionalState Then ' If the region is in a condition, then the state will be split and ' State.Assigned(will) be null. Merge to get sensible results. _endOfRegionState = Me.StateWhenTrue.Clone() IntersectWith(_endOfRegionState, Me.StateWhenFalse) Else _endOfRegionState = MyBase.State.Clone() End If Debug.Assert(Not _endOfRegionState.Assigned.IsNull) For Each branch In PendingBranches If IsInsideRegion(branch.Branch.Syntax.Span) AndAlso Not _labelsInside.Contains(branch.Label) Then IntersectWith(_endOfRegionState, branch.State) End If Next MyBase.LeaveRegion() End Sub Public Overrides Function VisitLabelStatement(node As BoundLabelStatement) As BoundNode If node.Syntax IsNot Nothing AndAlso IsInsideRegion(node.Syntax.Span) Then _labelsInside.Add(node.Label) End If Return MyBase.VisitLabelStatement(node) End Function Protected Overrides Sub ResolveBranch(pending As AbstractFlowPass(Of DataFlowPass.LocalState).PendingBranch, label As LabelSymbol, target As BoundLabelStatement, ByRef labelStateChanged As Boolean) If IsInside AndAlso pending.Branch IsNot Nothing AndAlso Not IsInsideRegion(pending.Branch.Syntax.Span) Then pending.State = If(pending.State.Reachable, ReachableState(), UnreachableState()) End If MyBase.ResolveBranch(pending, label, target, labelStateChanged) End Sub Protected Overrides Sub WriteArgument(arg As BoundExpression, isOut As Boolean) ' ref parameter must be '<Out()>' to "always" assign If isOut Then MyBase.WriteArgument(arg, isOut) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/NodeStateTable.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.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // A node table is the fundamental structure we use to track changes through the incremental // generator api. It can be thought of as a series of slots that take their input from an // upstream table and produce 0-or-more outputs. When viewed from a downstream table the outputs // are presented as a single unified list, with each output forming the new input to the downstream // table. // // Each slot has an associated state which is used to inform the operation that should be performed // to create or update the outputs. States generally flow through from upstream to downstream tables. // For instance an Added state implies that the upstream table produced a value that was not seen // in the previous iteration, and the table should run whatever transform it tracks on the input // to produce the outputs. These new outputs will also have a state of Added. A cached input specifies // that the input has not changed, and thus the outputs will be the same as the previous run. Added, // and Modified inputs will always run a transform to produce new outputs. Cached and Removed // entries will always use the previous entries and perform no work. // // It is important to track Removed entries while updating the downstream tables, as an upstream // remove can result in multiple downstream entries being removed. However, once all tables are up // to date, the removed entries are no longer needed, and the remaining entries can be considered to // be cached. This process is called 'compaction' and results in the actual tables which are stored // between runs, as opposed to the 'live' tables that exist during an update. // // Modified entries are similar to added inputs, but with a subtle difference. When an input is Added // all outputs are unconditionally added too. However when an input is modified, the outputs may still // be the same (for instance something changed elsewhere in a file that had no bearing on the produced // output). In this case, the state table checks the results against the previously produced values, // and any that are found to be the same instead get a cached state, meaning no new downstream work // will be produced for them. Thus a modified input is the only slot that can have differing output // states. internal enum EntryState { Added, Removed, Modified, Cached }; internal interface IStateTable { IStateTable AsCached(); } /// <summary> /// A data structure that tracks the inputs and output of an execution node /// </summary> /// <typeparam name="T">The type of the items tracked by this table</typeparam> internal sealed class NodeStateTable<T> : IStateTable { internal static NodeStateTable<T> Empty { get; } = new NodeStateTable<T>(ImmutableArray<TableEntry>.Empty, isCompacted: true); private readonly ImmutableArray<TableEntry> _states; private NodeStateTable(ImmutableArray<TableEntry> states, bool isCompacted) { Debug.Assert(!isCompacted || states.All(s => s.IsCached)); _states = states; IsCached = isCompacted; } public int Count { get => _states.Length; } /// <summary> /// Indicates if every entry in this table has a state of <see cref="EntryState.Cached"/> /// </summary> public bool IsCached { get; } public IEnumerator<(T item, EntryState state)> GetEnumerator() { foreach (var inputEntry in _states) { for (int i = 0; i < inputEntry.Count; i++) { yield return (inputEntry.GetItem(i), inputEntry.GetState(i)); } } } public NodeStateTable<T> AsCached() { if (IsCached) return this; var compacted = ArrayBuilder<TableEntry>.GetInstance(); foreach (var entry in _states) { if (!entry.IsRemoved) { compacted.Add(entry.AsCached()); } } return new NodeStateTable<T>(compacted.ToImmutableAndFree(), isCompacted: true); } IStateTable IStateTable.AsCached() => AsCached(); public T Single() { Debug.Assert((_states.Length == 1 || _states.Length == 2 && _states[0].IsRemoved) && this._states[^1].Count == 1); return this._states[^1].GetItem(0); } public ImmutableArray<T> Batch() { var sourceBuilder = ArrayBuilder<T>.GetInstance(); foreach (var entry in this) { // we don't return removed entries to the downstream node. // we're creating a new state table as part of this call, so they're no longer needed if (entry.state != EntryState.Removed) { sourceBuilder.Add(entry.item); } } return sourceBuilder.ToImmutableAndFree(); } public Builder ToBuilder() { return new Builder(this); } public sealed class Builder { private readonly ArrayBuilder<TableEntry> _states; private readonly NodeStateTable<T> _previous; internal Builder(NodeStateTable<T> previous) { _states = ArrayBuilder<TableEntry>.GetInstance(); _previous = previous; } public void RemoveEntries() { // if a new table is asked to remove entries we can just do nothing // as it can't have any effect on downstream tables if (_previous._states.Length > _states.Count) { var previousEntries = _previous._states[_states.Count].AsRemoved(); _states.Add(previousEntries); } } public bool TryUseCachedEntries() { if (_previous._states.Length <= _states.Count) { return false; } var previousEntries = _previous._states[_states.Count]; Debug.Assert(previousEntries.IsCached); _states.Add(previousEntries); return true; } public bool TryUseCachedEntries(out ImmutableArray<T> entries) { if (!TryUseCachedEntries()) { entries = default; return false; } entries = _states[_states.Count - 1].ToImmutableArray(); return true; } public bool TryModifyEntry(T value, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } Debug.Assert(_previous._states[_states.Count].Count == 1); _states.Add(new TableEntry(value, comparer.Equals(_previous._states[_states.Count].GetItem(0), value) ? EntryState.Cached : EntryState.Modified)); return true; } public bool TryModifyEntries(ImmutableArray<T> outputs, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } // Semantics: // For each item in the row, we compare with the new matching new value. // - Cached when the same // - Modified when different // - Removed when old item position > outputs.length // - Added when new item position < previousTable.length var previousEntry = _previous._states[_states.Count]; // when both entries have no items, we can short circuit if (previousEntry.Count == 0 && outputs.Length == 0) { _states.Add(previousEntry); return true; } var modified = new TableEntry.Builder(); var sharedCount = Math.Min(previousEntry.Count, outputs.Length); // cached or modified items for (int i = 0; i < sharedCount; i++) { var previous = previousEntry.GetItem(i); var replacement = outputs[i]; var entryState = comparer.Equals(previous, replacement) ? EntryState.Cached : EntryState.Modified; modified.Add(replacement, entryState); } // removed for (int i = sharedCount; i < previousEntry.Count; i++) { modified.Add(previousEntry.GetItem(i), EntryState.Removed); } // added for (int i = sharedCount; i < outputs.Length; i++) { modified.Add(outputs[i], EntryState.Added); } _states.Add(modified.ToImmutableAndFree()); return true; } public void AddEntry(T value, EntryState state) { _states.Add(new TableEntry(value, state)); } public void AddEntries(ImmutableArray<T> values, EntryState state) { _states.Add(new TableEntry(values, state)); } public NodeStateTable<T> ToImmutableAndFree() { if (_states.Count == 0) { _states.Free(); return NodeStateTable<T>.Empty; } var hasNonCached = _states.Any(static s => !s.IsCached); return new NodeStateTable<T>(_states.ToImmutableAndFree(), isCompacted: !hasNonCached); } } private readonly struct TableEntry { private static readonly ImmutableArray<EntryState> s_allAddedEntries = ImmutableArray.Create(EntryState.Added); private static readonly ImmutableArray<EntryState> s_allCachedEntries = ImmutableArray.Create(EntryState.Cached); private static readonly ImmutableArray<EntryState> s_allModifiedEntries = ImmutableArray.Create(EntryState.Modified); private static readonly ImmutableArray<EntryState> s_allRemovedEntries = ImmutableArray.Create(EntryState.Removed); private readonly ImmutableArray<T> _items; private readonly T? _item; /// <summary> /// Represents the corresponding state of each item in <see cref="_items"/>, /// or contains a single state when <see cref="_item"/> is populated or when every state of <see cref="_items"/> has the same value. /// </summary> private readonly ImmutableArray<EntryState> _states; public TableEntry(T item, EntryState state) : this(item, default, GetSingleArray(state)) { } public TableEntry(ImmutableArray<T> items, EntryState state) : this(default, items, GetSingleArray(state)) { } private TableEntry(T? item, ImmutableArray<T> items, ImmutableArray<EntryState> states) { Debug.Assert(!states.IsDefault); Debug.Assert(states.Length == 1 || states.Distinct().Count() > 1); this._item = item; this._items = items; this._states = states; } public bool IsCached => this._states == s_allCachedEntries || this._states.All(s => s == EntryState.Cached); public bool IsRemoved => this._states == s_allRemovedEntries || this._states.All(s => s == EntryState.Removed); public int Count => IsSingle ? 1 : _items.Length; public T GetItem(int index) { Debug.Assert(!IsSingle || index == 0); return IsSingle ? _item : _items[index]; } public EntryState GetState(int index) => _states.Length == 1 ? _states[0] : _states[index]; public ImmutableArray<T> ToImmutableArray() => IsSingle ? ImmutableArray.Create(_item) : _items; public TableEntry AsCached() => new(_item, _items, s_allCachedEntries); public TableEntry AsRemoved() => new(_item, _items, s_allRemovedEntries); [MemberNotNullWhen(true, new[] { nameof(_item) })] private bool IsSingle => this._items.IsDefault; private static ImmutableArray<EntryState> GetSingleArray(EntryState state) => state switch { EntryState.Added => s_allAddedEntries, EntryState.Cached => s_allCachedEntries, EntryState.Modified => s_allModifiedEntries, EntryState.Removed => s_allRemovedEntries, _ => throw ExceptionUtilities.Unreachable }; #if DEBUG public override string ToString() { if (IsSingle) { return $"{GetItem(0)}: {GetState(0)}"; } else { var sb = PooledStringBuilder.GetInstance(); sb.Builder.Append("{"); for (int i = 0; i < Count; i++) { if (i > 0) { sb.Builder.Append(','); } sb.Builder.Append(" ("); sb.Builder.Append(GetItem(i)); sb.Builder.Append(':'); sb.Builder.Append(GetState(i)); sb.Builder.Append(')'); } sb.Builder.Append(" }"); return sb.ToStringAndFree(); } } #endif public sealed class Builder { private readonly ArrayBuilder<T> _items = ArrayBuilder<T>.GetInstance(); private ArrayBuilder<EntryState>? _states; private EntryState? _currentState; public void Add(T item, EntryState state) { _items.Add(item); if (!_currentState.HasValue) { _currentState = state; } else if (_states is object) { _states.Add(state); } else if (_currentState != state) { _states = ArrayBuilder<EntryState>.GetInstance(_items.Count - 1, _currentState.Value); _states.Add(state); } } public TableEntry ToImmutableAndFree() { Debug.Assert(_currentState.HasValue, "Created a builder with no values?"); return new TableEntry(item: default, _items.ToImmutableAndFree(), _states?.ToImmutableAndFree() ?? GetSingleArray(_currentState.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; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { // A node table is the fundamental structure we use to track changes through the incremental // generator api. It can be thought of as a series of slots that take their input from an // upstream table and produce 0-or-more outputs. When viewed from a downstream table the outputs // are presented as a single unified list, with each output forming the new input to the downstream // table. // // Each slot has an associated state which is used to inform the operation that should be performed // to create or update the outputs. States generally flow through from upstream to downstream tables. // For instance an Added state implies that the upstream table produced a value that was not seen // in the previous iteration, and the table should run whatever transform it tracks on the input // to produce the outputs. These new outputs will also have a state of Added. A cached input specifies // that the input has not changed, and thus the outputs will be the same as the previous run. Added, // and Modified inputs will always run a transform to produce new outputs. Cached and Removed // entries will always use the previous entries and perform no work. // // It is important to track Removed entries while updating the downstream tables, as an upstream // remove can result in multiple downstream entries being removed. However, once all tables are up // to date, the removed entries are no longer needed, and the remaining entries can be considered to // be cached. This process is called 'compaction' and results in the actual tables which are stored // between runs, as opposed to the 'live' tables that exist during an update. // // Modified entries are similar to added inputs, but with a subtle difference. When an input is Added // all outputs are unconditionally added too. However when an input is modified, the outputs may still // be the same (for instance something changed elsewhere in a file that had no bearing on the produced // output). In this case, the state table checks the results against the previously produced values, // and any that are found to be the same instead get a cached state, meaning no new downstream work // will be produced for them. Thus a modified input is the only slot that can have differing output // states. internal enum EntryState { Added, Removed, Modified, Cached }; internal interface IStateTable { IStateTable AsCached(); } /// <summary> /// A data structure that tracks the inputs and output of an execution node /// </summary> /// <typeparam name="T">The type of the items tracked by this table</typeparam> internal sealed class NodeStateTable<T> : IStateTable { internal static NodeStateTable<T> Empty { get; } = new NodeStateTable<T>(ImmutableArray<TableEntry>.Empty, isCompacted: true); private readonly ImmutableArray<TableEntry> _states; private NodeStateTable(ImmutableArray<TableEntry> states, bool isCompacted) { Debug.Assert(!isCompacted || states.All(s => s.IsCached)); _states = states; IsCached = isCompacted; } public int Count { get => _states.Length; } /// <summary> /// Indicates if every entry in this table has a state of <see cref="EntryState.Cached"/> /// </summary> public bool IsCached { get; } public IEnumerator<(T item, EntryState state)> GetEnumerator() { foreach (var inputEntry in _states) { for (int i = 0; i < inputEntry.Count; i++) { yield return (inputEntry.GetItem(i), inputEntry.GetState(i)); } } } public NodeStateTable<T> AsCached() { if (IsCached) return this; var compacted = ArrayBuilder<TableEntry>.GetInstance(); foreach (var entry in _states) { if (!entry.IsRemoved) { compacted.Add(entry.AsCached()); } } return new NodeStateTable<T>(compacted.ToImmutableAndFree(), isCompacted: true); } IStateTable IStateTable.AsCached() => AsCached(); public T Single() { Debug.Assert((_states.Length == 1 || _states.Length == 2 && _states[0].IsRemoved) && this._states[^1].Count == 1); return this._states[^1].GetItem(0); } public ImmutableArray<T> Batch() { var sourceBuilder = ArrayBuilder<T>.GetInstance(); foreach (var entry in this) { // we don't return removed entries to the downstream node. // we're creating a new state table as part of this call, so they're no longer needed if (entry.state != EntryState.Removed) { sourceBuilder.Add(entry.item); } } return sourceBuilder.ToImmutableAndFree(); } public Builder ToBuilder() { return new Builder(this); } public sealed class Builder { private readonly ArrayBuilder<TableEntry> _states; private readonly NodeStateTable<T> _previous; internal Builder(NodeStateTable<T> previous) { _states = ArrayBuilder<TableEntry>.GetInstance(); _previous = previous; } public void RemoveEntries() { // if a new table is asked to remove entries we can just do nothing // as it can't have any effect on downstream tables if (_previous._states.Length > _states.Count) { var previousEntries = _previous._states[_states.Count].AsRemoved(); _states.Add(previousEntries); } } public bool TryUseCachedEntries() { if (_previous._states.Length <= _states.Count) { return false; } var previousEntries = _previous._states[_states.Count]; Debug.Assert(previousEntries.IsCached); _states.Add(previousEntries); return true; } public bool TryUseCachedEntries(out ImmutableArray<T> entries) { if (!TryUseCachedEntries()) { entries = default; return false; } entries = _states[_states.Count - 1].ToImmutableArray(); return true; } public bool TryModifyEntry(T value, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } Debug.Assert(_previous._states[_states.Count].Count == 1); _states.Add(new TableEntry(value, comparer.Equals(_previous._states[_states.Count].GetItem(0), value) ? EntryState.Cached : EntryState.Modified)); return true; } public bool TryModifyEntries(ImmutableArray<T> outputs, IEqualityComparer<T> comparer) { if (_previous._states.Length <= _states.Count) { return false; } // Semantics: // For each item in the row, we compare with the new matching new value. // - Cached when the same // - Modified when different // - Removed when old item position > outputs.length // - Added when new item position < previousTable.length var previousEntry = _previous._states[_states.Count]; // when both entries have no items, we can short circuit if (previousEntry.Count == 0 && outputs.Length == 0) { _states.Add(previousEntry); return true; } var modified = new TableEntry.Builder(); var sharedCount = Math.Min(previousEntry.Count, outputs.Length); // cached or modified items for (int i = 0; i < sharedCount; i++) { var previous = previousEntry.GetItem(i); var replacement = outputs[i]; var entryState = comparer.Equals(previous, replacement) ? EntryState.Cached : EntryState.Modified; modified.Add(replacement, entryState); } // removed for (int i = sharedCount; i < previousEntry.Count; i++) { modified.Add(previousEntry.GetItem(i), EntryState.Removed); } // added for (int i = sharedCount; i < outputs.Length; i++) { modified.Add(outputs[i], EntryState.Added); } _states.Add(modified.ToImmutableAndFree()); return true; } public void AddEntry(T value, EntryState state) { _states.Add(new TableEntry(value, state)); } public void AddEntries(ImmutableArray<T> values, EntryState state) { _states.Add(new TableEntry(values, state)); } public NodeStateTable<T> ToImmutableAndFree() { if (_states.Count == 0) { _states.Free(); return NodeStateTable<T>.Empty; } var hasNonCached = _states.Any(static s => !s.IsCached); return new NodeStateTable<T>(_states.ToImmutableAndFree(), isCompacted: !hasNonCached); } } private readonly struct TableEntry { private static readonly ImmutableArray<EntryState> s_allAddedEntries = ImmutableArray.Create(EntryState.Added); private static readonly ImmutableArray<EntryState> s_allCachedEntries = ImmutableArray.Create(EntryState.Cached); private static readonly ImmutableArray<EntryState> s_allModifiedEntries = ImmutableArray.Create(EntryState.Modified); private static readonly ImmutableArray<EntryState> s_allRemovedEntries = ImmutableArray.Create(EntryState.Removed); private readonly ImmutableArray<T> _items; private readonly T? _item; /// <summary> /// Represents the corresponding state of each item in <see cref="_items"/>, /// or contains a single state when <see cref="_item"/> is populated or when every state of <see cref="_items"/> has the same value. /// </summary> private readonly ImmutableArray<EntryState> _states; public TableEntry(T item, EntryState state) : this(item, default, GetSingleArray(state)) { } public TableEntry(ImmutableArray<T> items, EntryState state) : this(default, items, GetSingleArray(state)) { } private TableEntry(T? item, ImmutableArray<T> items, ImmutableArray<EntryState> states) { Debug.Assert(!states.IsDefault); Debug.Assert(states.Length == 1 || states.Distinct().Count() > 1); this._item = item; this._items = items; this._states = states; } public bool IsCached => this._states == s_allCachedEntries || this._states.All(s => s == EntryState.Cached); public bool IsRemoved => this._states == s_allRemovedEntries || this._states.All(s => s == EntryState.Removed); public int Count => IsSingle ? 1 : _items.Length; public T GetItem(int index) { Debug.Assert(!IsSingle || index == 0); return IsSingle ? _item : _items[index]; } public EntryState GetState(int index) => _states.Length == 1 ? _states[0] : _states[index]; public ImmutableArray<T> ToImmutableArray() => IsSingle ? ImmutableArray.Create(_item) : _items; public TableEntry AsCached() => new(_item, _items, s_allCachedEntries); public TableEntry AsRemoved() => new(_item, _items, s_allRemovedEntries); [MemberNotNullWhen(true, new[] { nameof(_item) })] private bool IsSingle => this._items.IsDefault; private static ImmutableArray<EntryState> GetSingleArray(EntryState state) => state switch { EntryState.Added => s_allAddedEntries, EntryState.Cached => s_allCachedEntries, EntryState.Modified => s_allModifiedEntries, EntryState.Removed => s_allRemovedEntries, _ => throw ExceptionUtilities.Unreachable }; #if DEBUG public override string ToString() { if (IsSingle) { return $"{GetItem(0)}: {GetState(0)}"; } else { var sb = PooledStringBuilder.GetInstance(); sb.Builder.Append("{"); for (int i = 0; i < Count; i++) { if (i > 0) { sb.Builder.Append(','); } sb.Builder.Append(" ("); sb.Builder.Append(GetItem(i)); sb.Builder.Append(':'); sb.Builder.Append(GetState(i)); sb.Builder.Append(')'); } sb.Builder.Append(" }"); return sb.ToStringAndFree(); } } #endif public sealed class Builder { private readonly ArrayBuilder<T> _items = ArrayBuilder<T>.GetInstance(); private ArrayBuilder<EntryState>? _states; private EntryState? _currentState; public void Add(T item, EntryState state) { _items.Add(item); if (!_currentState.HasValue) { _currentState = state; } else if (_states is object) { _states.Add(state); } else if (_currentState != state) { _states = ArrayBuilder<EntryState>.GetInstance(_items.Count - 1, _currentState.Value); _states.Add(state); } } public TableEntry ToImmutableAndFree() { Debug.Assert(_currentState.HasValue, "Created a builder with no values?"); return new TableEntry(item: default, _items.ToImmutableAndFree(), _states?.ToImmutableAndFree() ?? GetSingleArray(_currentState.Value)); } } } } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Compilers/Test/Core/Platform/Desktop/RuntimeAssemblyManager.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 #if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { internal sealed class RuntimeAssemblyManager : MarshalByRefObject, IDisposable { private enum Kind { ModuleData, Assembly } private struct AssemblyData { internal ModuleData ModuleData { get; } internal Assembly Assembly { get; } internal Kind Kind => Assembly != null ? Kind.Assembly : Kind.ModuleData; internal ModuleDataId Id => Assembly != null ? new ModuleDataId(Assembly, Assembly.ManifestModule.ModuleVersionId) : ModuleData.Id; internal AssemblyData(ModuleData moduleData) { ModuleData = moduleData; Assembly = null; } internal AssemblyData(Assembly assembly) { ModuleData = null; Assembly = assembly; } } private readonly AppDomainAssemblyCache _assemblyCache = AppDomainAssemblyCache.GetOrCreate(); private readonly Dictionary<string, AssemblyData> _fullNameToAssemblyDataMap; private readonly Dictionary<Guid, AssemblyData> _mvidToAssemblyDataMap; private readonly List<Guid> _mainMvids; // Assemblies loaded by this manager. private readonly HashSet<Assembly> _loadedAssemblies; /// <summary> /// The AppDomain we create to host the RuntimeAssemblyManager will always have the mscorlib /// it was compiled against. It's possible the data we are verifying or running used a slightly /// different mscorlib. Hence we can't do exact MVID matching on them. This tracks the set of /// modules loaded when we started the RuntimeAssemblyManager for which we can't do strict /// comparisons. /// </summary> private readonly HashSet<string> _preloadedSet; private bool _containsNetModules; internal IEnumerable<ModuleData> ModuleDatas => _fullNameToAssemblyDataMap.Values.Where(x => x.Kind == Kind.ModuleData).Select(x => x.ModuleData); public RuntimeAssemblyManager() { _fullNameToAssemblyDataMap = new Dictionary<string, AssemblyData>(StringComparer.OrdinalIgnoreCase); _mvidToAssemblyDataMap = new Dictionary<Guid, AssemblyData>(); _loadedAssemblies = new HashSet<Assembly>(); _mainMvids = new List<Guid>(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += AssemblyResolve; currentDomain.AssemblyLoad += AssemblyLoad; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolve; _preloadedSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var assembly in currentDomain.GetAssemblies()) { var assemblyData = new AssemblyData(assembly); _preloadedSet.Add(assemblyData.Id.SimpleName); AddAssemblyData(assemblyData); } } public string DumpAssemblyData(out string dumpDirectory) { return RuntimeEnvironmentUtilities.DumpAssemblyData(ModuleDatas, out dumpDirectory); } public void Dispose() { // clean up our handlers, so that they don't accumulate AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve; AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoad; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= ReflectionOnlyAssemblyResolve; foreach (var assembly in _loadedAssemblies) { if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve -= ModuleResolve; } } //EDMAURER Some RuntimeAssemblyManagers are created via reflection in an AppDomain of our creation. //Sometimes those AppDomains are not released. I don't fully understand how that appdomain roots //a RuntimeAssemblyManager, but according to heap dumps, it does. Even though the appdomain is not //unloaded, its RuntimeAssemblyManager is explicitly disposed. So make sure that it cleans up this //memory hog - the modules dictionary. _fullNameToAssemblyDataMap.Clear(); _mvidToAssemblyDataMap.Clear(); } /// <summary> /// Adds given MVID into a list of module MVIDs that are considered owned by this manager. /// </summary> public void AddMainModuleMvid(Guid mvid) { if (!_mvidToAssemblyDataMap.ContainsKey(mvid)) { throw new Exception($"No module with {mvid} loaded"); } _mainMvids.Add(mvid); } /// <summary> /// True if given assembly is owned by this manager. /// </summary> private bool IsOwned(Assembly assembly) { if (assembly == null) { return false; } return _mainMvids.Count == 0 || (assembly.ManifestModule != null && _mainMvids.Contains(assembly.ManifestModule.ModuleVersionId)) || _loadedAssemblies.Contains(assembly); } public bool ContainsNetModules() { return _containsNetModules; } public override object InitializeLifetimeService() { return null; } /// <summary> /// Add this to the set of <see cref="ModuleData"/> that is managed by this instance. It is okay to /// return values that are already present. /// </summary> /// <param name="modules"></param> public void AddModuleData(List<RuntimeModuleData> modules) { foreach (var module in modules.Select(x => x.Data)) { if (TryGetMatchingByFullName(module.Id, out var assemblyData, out var fullMatch)) { if (!fullMatch) { throw new Exception($"Two modules of name {assemblyData.Id.FullName} have different MVID"); } } else { if (module.Kind == OutputKind.NetModule) { _containsNetModules = true; } AddAssemblyData(new AssemblyData(module)); } } } public bool HasConflicts(List<RuntimeModuleDataId> moduleDataIds) { foreach (var id in moduleDataIds.Select(x => x.Id)) { if (TryGetMatchingByFullName(id, out _, out var fullMatch) && !fullMatch) { return true; } if (TryGetMatchingByMvid(id, out _, out fullMatch) && !fullMatch) { return true; } } return false; } private void AddAssemblyData(AssemblyData assemblyData) { _fullNameToAssemblyDataMap.Add(assemblyData.Id.FullName, assemblyData); _mvidToAssemblyDataMap.Add(assemblyData.Id.Mvid, assemblyData); } /// <summary> /// Return the subset of IDs passed in which are not currently tracked by this instance. /// </summary> public List<RuntimeModuleDataId> GetMissing(List<RuntimeModuleDataId> moduleIds) { var list = new List<RuntimeModuleDataId>(); foreach (var id in moduleIds.Select(x => x.Id)) { if (!TryGetMatchingByFullName(id, out var other, out var fullMatch) || !fullMatch) { list.Add(new RuntimeModuleDataId(id)); } } return list; } private bool TryGetMatchingByFullName(ModuleDataId id, out AssemblyData assemblyData, out bool fullMatch) { if (_fullNameToAssemblyDataMap.TryGetValue(id.FullName, out assemblyData)) { fullMatch = _preloadedSet.Contains(id.SimpleName) || id.Mvid == assemblyData.Id.Mvid; return true; } assemblyData = default(AssemblyData); fullMatch = false; return false; } private bool TryGetMatchingByMvid(ModuleDataId id, out AssemblyData assemblyData, out bool fullMatch) { if (_mvidToAssemblyDataMap.TryGetValue(id.Mvid, out assemblyData)) { fullMatch = _preloadedSet.Contains(id.SimpleName) || StringComparer.OrdinalIgnoreCase.Equals(id.FullName, assemblyData.Id.FullName); return true; } assemblyData = default(AssemblyData); fullMatch = false; return false; } private ImmutableArray<byte> GetModuleBytesByName(string moduleName) { if (!_fullNameToAssemblyDataMap.TryGetValue(moduleName, out var data)) { throw new KeyNotFoundException(String.Format("Could not find image for module '{0}'.", moduleName)); } if (data.Kind != Kind.ModuleData) { throw new Exception($"Cannot get bytes for preloaded Assembly {data.Id.FullName}"); } return data.ModuleData.Image; } private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { var assembly = args.LoadedAssembly; // ModuleResolve needs to be hooked up for the main assembly once its loaded. // We won't get an AssemblyResolve event for the main assembly so we need to do it here. if (_mainMvids.Contains(assembly.ManifestModule.ModuleVersionId) && _loadedAssemblies.Add(assembly)) { if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve += ModuleResolve; } } } private Assembly AssemblyResolve(object sender, ResolveEventArgs args) { return AssemblyResolve(args, reflectionOnly: false); } private Assembly ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { return AssemblyResolve(args, reflectionOnly: true); } private Assembly AssemblyResolve(ResolveEventArgs args, bool reflectionOnly) { // only respond to requests for dependencies of assemblies owned by this manager: if (IsOwned(args.RequestingAssembly)) { return GetAssembly(args.Name, reflectionOnly); } return null; } private Assembly GetAssembly(string fullName, bool reflectionOnly) { if (!_fullNameToAssemblyDataMap.TryGetValue(fullName, out var data)) { return null; } Assembly assembly; switch (data.Kind) { case Kind.Assembly: assembly = data.Assembly; if (reflectionOnly && !assembly.ReflectionOnly) { assembly = Assembly.ReflectionOnlyLoad(assembly.FullName); } break; case Kind.ModuleData: assembly = _assemblyCache.GetOrLoad(data.ModuleData, reflectionOnly); break; default: throw new InvalidOperationException(); } if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve += ModuleResolve; } _loadedAssemblies.Add(assembly); return assembly; } private Module ModuleResolve(object sender, ResolveEventArgs args) { var assembly = args.RequestingAssembly; var rawModule = GetModuleBytesByName(args.Name); Debug.Assert(assembly != null); Debug.Assert(!rawModule.IsDefault); return assembly.LoadModule(args.Name, rawModule.ToArray()); } public SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName, List<RuntimeModuleDataId> searchModules) { try { var signatures = new SortedSet<string>(); foreach (var id in searchModules.Select(x => x.Id)) // Check inside each assembly in the compilation { var assembly = GetAssembly(id.FullName, reflectionOnly: true); foreach (var signature in MetadataSignatureHelper.GetMemberSignatures(assembly, fullyQualifiedTypeName, memberName)) { signatures.Add(signature); } } return signatures; } catch (Exception ex) { var builder = new StringBuilder(); builder.AppendLine($"Error getting signatures {fullyQualifiedTypeName}.{memberName}: {ex.Message}"); builder.AppendLine($"Assemblies:"); foreach (var module in _fullNameToAssemblyDataMap.Values) { builder.AppendLine($"\t{module.Id.SimpleName} {module.Id.Mvid} - {module.Kind} {_assemblyCache.GetOrDefault(module.Id, reflectionOnly: false) != null} {_assemblyCache.GetOrDefault(module.Id, reflectionOnly: true) != null}"); } throw new Exception(builder.ToString(), ex); } } private SortedSet<string> GetFullyQualifiedTypeNames(string assemblyName) { var typeNames = new SortedSet<string>(); Assembly assembly = GetAssembly(assemblyName, true); foreach (var typ in assembly.GetTypes()) typeNames.Add(typ.FullName); return typeNames; } public int Execute(string moduleName, string[] mainArgs, int? expectedOutputLength, out string output) { ImmutableArray<byte> bytes = GetModuleBytesByName(moduleName); Assembly assembly = DesktopRuntimeUtil.LoadAsAssembly(moduleName, bytes); MethodInfo entryPoint = assembly.EntryPoint; Debug.Assert(entryPoint != null, "Attempting to execute an assembly that has no entrypoint; is your test trying to execute a DLL?"); object result = null; DesktopRuntimeEnvironment.Capture(() => { var count = entryPoint.GetParameters().Length; object[] args; if (count == 0) { args = new object[0]; } else if (count == 1) { args = new object[] { mainArgs ?? new string[0] }; } else { throw new Exception("Unrecognized entry point"); } result = entryPoint.Invoke(null, args); }, expectedOutputLength ?? 0, out var stdOut, out var stdErr); output = stdOut + stdErr; return result is int ? (int)result : 0; } public string[] PeVerifyModules(string[] modulesToVerify, bool throwOnError = true) { // For Windows RT (ARM) THE CLRHelper.Peverify appears to not work and will exclude this // for ARM testing at present. StringBuilder errors = new StringBuilder(); List<string> allOutput = new List<string>(); foreach (var name in modulesToVerify) { var assemblyData = _fullNameToAssemblyDataMap[name]; if (assemblyData.Kind != Kind.ModuleData) { continue; } var module = assemblyData.ModuleData; string[] output = CLRHelpers.PeVerify(module.Image); if (output.Length > 0) { if (modulesToVerify.Length > 1) { errors.AppendLine(); errors.AppendLine("<<" + name + ">>"); errors.AppendLine(); } foreach (var error in output) { errors.AppendLine(error); } } if (!throwOnError) { allOutput.AddRange(output); } } if (throwOnError && errors.Length > 0) { RuntimeEnvironmentUtilities.DumpAssemblyData(ModuleDatas, out var dumpDir); throw new RuntimePeVerifyException(errors.ToString(), dumpDir); } return allOutput.ToArray(); } } } #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. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Roslyn.Test.Utilities.Desktop { internal sealed class RuntimeAssemblyManager : MarshalByRefObject, IDisposable { private enum Kind { ModuleData, Assembly } private struct AssemblyData { internal ModuleData ModuleData { get; } internal Assembly Assembly { get; } internal Kind Kind => Assembly != null ? Kind.Assembly : Kind.ModuleData; internal ModuleDataId Id => Assembly != null ? new ModuleDataId(Assembly, Assembly.ManifestModule.ModuleVersionId) : ModuleData.Id; internal AssemblyData(ModuleData moduleData) { ModuleData = moduleData; Assembly = null; } internal AssemblyData(Assembly assembly) { ModuleData = null; Assembly = assembly; } } private readonly AppDomainAssemblyCache _assemblyCache = AppDomainAssemblyCache.GetOrCreate(); private readonly Dictionary<string, AssemblyData> _fullNameToAssemblyDataMap; private readonly Dictionary<Guid, AssemblyData> _mvidToAssemblyDataMap; private readonly List<Guid> _mainMvids; // Assemblies loaded by this manager. private readonly HashSet<Assembly> _loadedAssemblies; /// <summary> /// The AppDomain we create to host the RuntimeAssemblyManager will always have the mscorlib /// it was compiled against. It's possible the data we are verifying or running used a slightly /// different mscorlib. Hence we can't do exact MVID matching on them. This tracks the set of /// modules loaded when we started the RuntimeAssemblyManager for which we can't do strict /// comparisons. /// </summary> private readonly HashSet<string> _preloadedSet; private bool _containsNetModules; internal IEnumerable<ModuleData> ModuleDatas => _fullNameToAssemblyDataMap.Values.Where(x => x.Kind == Kind.ModuleData).Select(x => x.ModuleData); public RuntimeAssemblyManager() { _fullNameToAssemblyDataMap = new Dictionary<string, AssemblyData>(StringComparer.OrdinalIgnoreCase); _mvidToAssemblyDataMap = new Dictionary<Guid, AssemblyData>(); _loadedAssemblies = new HashSet<Assembly>(); _mainMvids = new List<Guid>(); var currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += AssemblyResolve; currentDomain.AssemblyLoad += AssemblyLoad; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += ReflectionOnlyAssemblyResolve; _preloadedSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var assembly in currentDomain.GetAssemblies()) { var assemblyData = new AssemblyData(assembly); _preloadedSet.Add(assemblyData.Id.SimpleName); AddAssemblyData(assemblyData); } } public string DumpAssemblyData(out string dumpDirectory) { return RuntimeEnvironmentUtilities.DumpAssemblyData(ModuleDatas, out dumpDirectory); } public void Dispose() { // clean up our handlers, so that they don't accumulate AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve; AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoad; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= ReflectionOnlyAssemblyResolve; foreach (var assembly in _loadedAssemblies) { if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve -= ModuleResolve; } } //EDMAURER Some RuntimeAssemblyManagers are created via reflection in an AppDomain of our creation. //Sometimes those AppDomains are not released. I don't fully understand how that appdomain roots //a RuntimeAssemblyManager, but according to heap dumps, it does. Even though the appdomain is not //unloaded, its RuntimeAssemblyManager is explicitly disposed. So make sure that it cleans up this //memory hog - the modules dictionary. _fullNameToAssemblyDataMap.Clear(); _mvidToAssemblyDataMap.Clear(); } /// <summary> /// Adds given MVID into a list of module MVIDs that are considered owned by this manager. /// </summary> public void AddMainModuleMvid(Guid mvid) { if (!_mvidToAssemblyDataMap.ContainsKey(mvid)) { throw new Exception($"No module with {mvid} loaded"); } _mainMvids.Add(mvid); } /// <summary> /// True if given assembly is owned by this manager. /// </summary> private bool IsOwned(Assembly assembly) { if (assembly == null) { return false; } return _mainMvids.Count == 0 || (assembly.ManifestModule != null && _mainMvids.Contains(assembly.ManifestModule.ModuleVersionId)) || _loadedAssemblies.Contains(assembly); } public bool ContainsNetModules() { return _containsNetModules; } public override object InitializeLifetimeService() { return null; } /// <summary> /// Add this to the set of <see cref="ModuleData"/> that is managed by this instance. It is okay to /// return values that are already present. /// </summary> /// <param name="modules"></param> public void AddModuleData(List<RuntimeModuleData> modules) { foreach (var module in modules.Select(x => x.Data)) { if (TryGetMatchingByFullName(module.Id, out var assemblyData, out var fullMatch)) { if (!fullMatch) { throw new Exception($"Two modules of name {assemblyData.Id.FullName} have different MVID"); } } else { if (module.Kind == OutputKind.NetModule) { _containsNetModules = true; } AddAssemblyData(new AssemblyData(module)); } } } public bool HasConflicts(List<RuntimeModuleDataId> moduleDataIds) { foreach (var id in moduleDataIds.Select(x => x.Id)) { if (TryGetMatchingByFullName(id, out _, out var fullMatch) && !fullMatch) { return true; } if (TryGetMatchingByMvid(id, out _, out fullMatch) && !fullMatch) { return true; } } return false; } private void AddAssemblyData(AssemblyData assemblyData) { _fullNameToAssemblyDataMap.Add(assemblyData.Id.FullName, assemblyData); _mvidToAssemblyDataMap.Add(assemblyData.Id.Mvid, assemblyData); } /// <summary> /// Return the subset of IDs passed in which are not currently tracked by this instance. /// </summary> public List<RuntimeModuleDataId> GetMissing(List<RuntimeModuleDataId> moduleIds) { var list = new List<RuntimeModuleDataId>(); foreach (var id in moduleIds.Select(x => x.Id)) { if (!TryGetMatchingByFullName(id, out var other, out var fullMatch) || !fullMatch) { list.Add(new RuntimeModuleDataId(id)); } } return list; } private bool TryGetMatchingByFullName(ModuleDataId id, out AssemblyData assemblyData, out bool fullMatch) { if (_fullNameToAssemblyDataMap.TryGetValue(id.FullName, out assemblyData)) { fullMatch = _preloadedSet.Contains(id.SimpleName) || id.Mvid == assemblyData.Id.Mvid; return true; } assemblyData = default(AssemblyData); fullMatch = false; return false; } private bool TryGetMatchingByMvid(ModuleDataId id, out AssemblyData assemblyData, out bool fullMatch) { if (_mvidToAssemblyDataMap.TryGetValue(id.Mvid, out assemblyData)) { fullMatch = _preloadedSet.Contains(id.SimpleName) || StringComparer.OrdinalIgnoreCase.Equals(id.FullName, assemblyData.Id.FullName); return true; } assemblyData = default(AssemblyData); fullMatch = false; return false; } private ImmutableArray<byte> GetModuleBytesByName(string moduleName) { if (!_fullNameToAssemblyDataMap.TryGetValue(moduleName, out var data)) { throw new KeyNotFoundException(String.Format("Could not find image for module '{0}'.", moduleName)); } if (data.Kind != Kind.ModuleData) { throw new Exception($"Cannot get bytes for preloaded Assembly {data.Id.FullName}"); } return data.ModuleData.Image; } private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { var assembly = args.LoadedAssembly; // ModuleResolve needs to be hooked up for the main assembly once its loaded. // We won't get an AssemblyResolve event for the main assembly so we need to do it here. if (_mainMvids.Contains(assembly.ManifestModule.ModuleVersionId) && _loadedAssemblies.Add(assembly)) { if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve += ModuleResolve; } } } private Assembly AssemblyResolve(object sender, ResolveEventArgs args) { return AssemblyResolve(args, reflectionOnly: false); } private Assembly ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) { return AssemblyResolve(args, reflectionOnly: true); } private Assembly AssemblyResolve(ResolveEventArgs args, bool reflectionOnly) { // only respond to requests for dependencies of assemblies owned by this manager: if (IsOwned(args.RequestingAssembly)) { return GetAssembly(args.Name, reflectionOnly); } return null; } private Assembly GetAssembly(string fullName, bool reflectionOnly) { if (!_fullNameToAssemblyDataMap.TryGetValue(fullName, out var data)) { return null; } Assembly assembly; switch (data.Kind) { case Kind.Assembly: assembly = data.Assembly; if (reflectionOnly && !assembly.ReflectionOnly) { assembly = Assembly.ReflectionOnlyLoad(assembly.FullName); } break; case Kind.ModuleData: assembly = _assemblyCache.GetOrLoad(data.ModuleData, reflectionOnly); break; default: throw new InvalidOperationException(); } if (!MonoHelpers.IsRunningOnMono()) { assembly.ModuleResolve += ModuleResolve; } _loadedAssemblies.Add(assembly); return assembly; } private Module ModuleResolve(object sender, ResolveEventArgs args) { var assembly = args.RequestingAssembly; var rawModule = GetModuleBytesByName(args.Name); Debug.Assert(assembly != null); Debug.Assert(!rawModule.IsDefault); return assembly.LoadModule(args.Name, rawModule.ToArray()); } public SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName, List<RuntimeModuleDataId> searchModules) { try { var signatures = new SortedSet<string>(); foreach (var id in searchModules.Select(x => x.Id)) // Check inside each assembly in the compilation { var assembly = GetAssembly(id.FullName, reflectionOnly: true); foreach (var signature in MetadataSignatureHelper.GetMemberSignatures(assembly, fullyQualifiedTypeName, memberName)) { signatures.Add(signature); } } return signatures; } catch (Exception ex) { var builder = new StringBuilder(); builder.AppendLine($"Error getting signatures {fullyQualifiedTypeName}.{memberName}: {ex.Message}"); builder.AppendLine($"Assemblies:"); foreach (var module in _fullNameToAssemblyDataMap.Values) { builder.AppendLine($"\t{module.Id.SimpleName} {module.Id.Mvid} - {module.Kind} {_assemblyCache.GetOrDefault(module.Id, reflectionOnly: false) != null} {_assemblyCache.GetOrDefault(module.Id, reflectionOnly: true) != null}"); } throw new Exception(builder.ToString(), ex); } } private SortedSet<string> GetFullyQualifiedTypeNames(string assemblyName) { var typeNames = new SortedSet<string>(); Assembly assembly = GetAssembly(assemblyName, true); foreach (var typ in assembly.GetTypes()) typeNames.Add(typ.FullName); return typeNames; } public int Execute(string moduleName, string[] mainArgs, int? expectedOutputLength, out string output) { ImmutableArray<byte> bytes = GetModuleBytesByName(moduleName); Assembly assembly = DesktopRuntimeUtil.LoadAsAssembly(moduleName, bytes); MethodInfo entryPoint = assembly.EntryPoint; Debug.Assert(entryPoint != null, "Attempting to execute an assembly that has no entrypoint; is your test trying to execute a DLL?"); object result = null; DesktopRuntimeEnvironment.Capture(() => { var count = entryPoint.GetParameters().Length; object[] args; if (count == 0) { args = new object[0]; } else if (count == 1) { args = new object[] { mainArgs ?? new string[0] }; } else { throw new Exception("Unrecognized entry point"); } result = entryPoint.Invoke(null, args); }, expectedOutputLength ?? 0, out var stdOut, out var stdErr); output = stdOut + stdErr; return result is int ? (int)result : 0; } public string[] PeVerifyModules(string[] modulesToVerify, bool throwOnError = true) { // For Windows RT (ARM) THE CLRHelper.Peverify appears to not work and will exclude this // for ARM testing at present. StringBuilder errors = new StringBuilder(); List<string> allOutput = new List<string>(); foreach (var name in modulesToVerify) { var assemblyData = _fullNameToAssemblyDataMap[name]; if (assemblyData.Kind != Kind.ModuleData) { continue; } var module = assemblyData.ModuleData; string[] output = CLRHelpers.PeVerify(module.Image); if (output.Length > 0) { if (modulesToVerify.Length > 1) { errors.AppendLine(); errors.AppendLine("<<" + name + ">>"); errors.AppendLine(); } foreach (var error in output) { errors.AppendLine(error); } } if (!throwOnError) { allOutput.AddRange(output); } } if (throwOnError && errors.Length > 0) { RuntimeEnvironmentUtilities.DumpAssemblyData(ModuleDatas, out var dumpDir); throw new RuntimePeVerifyException(errors.ToString(), dumpDir); } return allOutput.ToArray(); } } } #endif
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaDocumentationCommentFormatting.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.Threading; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static class PythiaDocumentationCommentFormatting { public static IEnumerable<TaggedText> GetDocumentationParts(ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) => Shared.Extensions.ISymbolExtensions2.GetDocumentationParts(symbol, semanticModel, position, formatter, 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.Generic; using System.Threading; using Microsoft.CodeAnalysis.DocumentationComments; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static class PythiaDocumentationCommentFormatting { public static IEnumerable<TaggedText> GetDocumentationParts(ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) => Shared.Extensions.ISymbolExtensions2.GetDocumentationParts(symbol, semanticModel, position, formatter, cancellationToken); } }
-1
dotnet/roslyn
56,257
Null annotate IDocumentNavigationService
jasonmalinowski
"2021-09-08T19:59:35Z"
"2021-09-08T21:24:36Z"
04cef9860ed6b6a6d97c35e0053149f4117f3a10
ef6e65fa1185f7aff571277420227446bf6eafa0
Null annotate IDocumentNavigationService.
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/VisualBasicCodeRefactoringVerifier`1.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Testing; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeRefactoringVerifier<TCodeRefactoring> where TCodeRefactoring : CodeRefactoringProvider, new() { /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, string)"/> public static Task VerifyRefactoringAsync(string source, string fixedSource) { return VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); } /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/> public static Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource) { return VerifyRefactoringAsync(source, new[] { expected }, fixedSource); } /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/> public static Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource }; test.ExpectedDiagnostics.AddRange(expected); return test.RunAsync(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. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Testing; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public static partial class VisualBasicCodeRefactoringVerifier<TCodeRefactoring> where TCodeRefactoring : CodeRefactoringProvider, new() { /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, string)"/> public static Task VerifyRefactoringAsync(string source, string fixedSource) { return VerifyRefactoringAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource); } /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult, string)"/> public static Task VerifyRefactoringAsync(string source, DiagnosticResult expected, string fixedSource) { return VerifyRefactoringAsync(source, new[] { expected }, fixedSource); } /// <inheritdoc cref="CodeRefactoringVerifier{TCodeRefactoring, TTest, TVerifier}.VerifyRefactoringAsync(string, DiagnosticResult[], string)"/> public static Task VerifyRefactoringAsync(string source, DiagnosticResult[] expected, string fixedSource) { var test = new Test { TestCode = source, FixedCode = fixedSource }; test.ExpectedDiagnostics.AddRange(expected); return test.RunAsync(CancellationToken.None); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/Test2/Compilation/CompilationTests.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.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests <[UseExportProvider]> Public Class CompilationTests Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName) End Function <Fact> <WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")> Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task Dim workspaceDefinition = <Workspace> <Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true"> <Document> var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations </Document> </Project> </Workspace> Dim composition = EditorTestCompositions.EditorFeatures.AddParts( GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition) Dim project = GetProject(workspace.CurrentSolution, "TestAssembly") Assert.Null(Await project.GetCompilationAsync()) Assert.Null(Await project.GetCompilationAsync()) End Using 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.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests <[UseExportProvider]> Public Class CompilationTests Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName) End Function <Fact> <WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")> Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task Dim workspaceDefinition = <Workspace> <Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true"> <Document> var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations </Document> </Project> </Workspace> Dim composition = EditorTestCompositions.EditorFeatures.AddParts( GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition) Dim project = GetProject(workspace.CurrentSolution, "TestAssembly") Assert.Null(Await project.GetCompilationAsync()) Assert.Null(Await project.GetCompilationAsync()) End Using End Function End Class End Namespace
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/NavigateTo/AbstractNavigateToSearchService.InProcess.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal abstract partial class AbstractNavigateToSearchService { private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs = ImmutableArray.Create( (PatternMatchKind.Exact, NavigateToMatchKind.Exact), (PatternMatchKind.Prefix, NavigateToMatchKind.Prefix), (PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact), (PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix), (PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix), (PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring), (PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring), (PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy), // Map our value to 'Fuzzy' as that's the lower value the platform supports. (PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy)); public static Task SearchFullyLoadedProjectInCurrentProcessAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken); } public static Task SearchFullyLoadedDocumentInCurrentProcessAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( document.Project, priorityDocuments: ImmutableArray<Document>.Empty, document, searchPattern, kinds, onResultFound, cancellationToken); } private static async Task FindSearchResultsAsync( Project project, ImmutableArray<Document> priorityDocuments, Document? searchDocument, string pattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); // Prioritize the active documents if we have any. var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false); // Then process non-priority documents. var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false); // if the caller is only searching a single doc, and we already covered it above, don't bother computing // source-generator docs. if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument))) return; // Finally, generate and process and source-generated docs. this may take some time, so we always want to // do this after the other documents. var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false); } private static async Task ProcessDocumentsAsync( Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var document in documents) { if (searchDocument != null && searchDocument != document) continue; cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(() => ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessDocumentAsync( Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false); await ProcessIndexAsync( document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false); } public static async Task SearchCachedDocumentsInCurrentProcessAsync( Workspace workspace, ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onItemFound, CancellationToken cancellationToken) { var stringTable = new StringTable(); var highPriDocsSet = priorityDocumentKeys.ToSet(); var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d)); // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); await SearchCachedDocumentsInCurrentProcessAsync( workspace, priorityDocumentKeys, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); await SearchCachedDocumentsInCurrentProcessAsync( workspace, lowPriDocs, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); } private static async Task SearchCachedDocumentsInCurrentProcessAsync( Workspace workspace, ImmutableArray<DocumentKey> documentKeys, string patternName, string patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onItemFound, StringTable stringTable, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var documentKey in documentKeys) { tasks.Add(Task.Run(async () => { var index = await SyntaxTreeIndex.LoadAsync( workspace, documentKey, checksum: null, stringTable, cancellationToken).ConfigureAwait(false); if (index == null) return; await ProcessIndexAsync( documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessIndexAsync( DocumentId documentId, Document? document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, SyntaxTreeIndex index, CancellationToken cancellationToken) { var containerMatcher = patternContainer != null ? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer) : null; using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true); using var _1 = containerMatcher; foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos) { // Namespaces are never returned in nav-to as they're too common and have too many locations. if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Namespace) continue; await AddResultIfMatchAsync( documentId, document, declaredSymbolInfo, nameMatcher, containerMatcher, kinds, onResultFound, cancellationToken).ConfigureAwait(false); } } private static async Task AddResultIfMatchAsync( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, PatternMatcher nameMatcher, PatternMatcher? containerMatcher, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { using var nameMatches = TemporaryArray<PatternMatch>.Empty; using var containerMatches = TemporaryArray<PatternMatch>.Empty; cancellationToken.ThrowIfCancellationRequested(); if (kinds.Contains(declaredSymbolInfo.Kind) && nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) && containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false) { // See if we have a match in a linked file. If so, see if we have the same match in // other projects that this file is linked in. If so, include the full set of projects // the match is in so we can display that well in the UI. // // We can only do this in the case where the solution is loaded and thus we can examine // the relationship between this document and the other documents linked to it. In the // case where the solution isn't fully loaded and we're just reading in cached data, we // don't know what other files we're linked to and can't merge results in this fashion. var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync( document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false); var result = ConvertResult( documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects); await onResultFound(result).ConfigureAwait(false); } } private static RoslynNavigateToItem ConvertResult( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, in TemporaryArray<PatternMatch> nameMatches, in TemporaryArray<PatternMatch> containerMatches, ImmutableArray<ProjectId> additionalMatchingProjects) { var matchKind = GetNavigateToMatchKind(nameMatches); // A match is considered to be case sensitive if all its constituent pattern matches are // case sensitive. var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive); var kind = GetItemKind(declaredSymbolInfo); using var matchedSpans = TemporaryArray<TextSpan>.Empty; foreach (var match in nameMatches) matchedSpans.AddRange(match.MatchedSpans); // If we were not given a Document instance, then we're finding matches in cached data // and thus could be 'stale'. return new RoslynNavigateToItem( isStale: document == null, documentId, additionalMatchingProjects, declaredSymbolInfo, kind, matchKind, isCaseSensitive, matchedSpans.ToImmutableAndClear()); } private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync( Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken) { if (document == null) return ImmutableArray<ProjectId>.Empty; using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result); var solution = document.Project.Solution; var linkedDocumentIds = document.GetLinkedDocumentIds(); foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false); // See if the index for the other file also contains this same info. If so, merge the results so the // user only sees them as a single hit in the UI. if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo)) result.Add(linkedDocument.Project.Id); } result.RemoveDuplicates(); return result.ToImmutable(); } private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo) { switch (declaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: return NavigateToItemKind.Class; case DeclaredSymbolInfoKind.RecordStruct: return NavigateToItemKind.Structure; case DeclaredSymbolInfoKind.Constant: return NavigateToItemKind.Constant; case DeclaredSymbolInfoKind.Delegate: return NavigateToItemKind.Delegate; case DeclaredSymbolInfoKind.Enum: return NavigateToItemKind.Enum; case DeclaredSymbolInfoKind.EnumMember: return NavigateToItemKind.EnumItem; case DeclaredSymbolInfoKind.Event: return NavigateToItemKind.Event; case DeclaredSymbolInfoKind.Field: return NavigateToItemKind.Field; case DeclaredSymbolInfoKind.Interface: return NavigateToItemKind.Interface; case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Method: return NavigateToItemKind.Method; case DeclaredSymbolInfoKind.Module: return NavigateToItemKind.Module; case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Property: return NavigateToItemKind.Property; case DeclaredSymbolInfoKind.Struct: return NavigateToItemKind.Structure; default: throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind); } } private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches) { // work backwards through the match kinds. That way our result is as bad as our worst match part. For // example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and // `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and // thus as good as `Console.Write`. for (var i = s_kindPairs.Length - 1; i >= 0; i--) { var (roslynKind, vsKind) = s_kindPairs[i]; foreach (var match in nameMatches) { if (match.Kind == roslynKind) return vsKind; } } return NavigateToMatchKind.Regular; } private readonly struct DeclaredSymbolInfoKindSet { private readonly ImmutableArray<bool> _lookupTable; public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds) { // The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned. Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte)); var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length]; foreach (var navigateToItemKind in navigateToItemKinds) { switch (navigateToItemKind) { case NavigateToItemKind.Class: lookupTable[(int)DeclaredSymbolInfoKind.Class] = true; lookupTable[(int)DeclaredSymbolInfoKind.Record] = true; break; case NavigateToItemKind.Constant: lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true; break; case NavigateToItemKind.Delegate: lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true; break; case NavigateToItemKind.Enum: lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true; break; case NavigateToItemKind.EnumItem: lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true; break; case NavigateToItemKind.Event: lookupTable[(int)DeclaredSymbolInfoKind.Event] = true; break; case NavigateToItemKind.Field: lookupTable[(int)DeclaredSymbolInfoKind.Field] = true; break; case NavigateToItemKind.Interface: lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true; break; case NavigateToItemKind.Method: lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true; lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true; lookupTable[(int)DeclaredSymbolInfoKind.Method] = true; break; case NavigateToItemKind.Module: lookupTable[(int)DeclaredSymbolInfoKind.Module] = true; break; case NavigateToItemKind.Property: lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true; lookupTable[(int)DeclaredSymbolInfoKind.Property] = true; break; case NavigateToItemKind.Structure: lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true; lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true; break; default: // Not a recognized symbol info kind break; } } _lookupTable = ImmutableArray.CreateRange(lookupTable); } public bool Contains(DeclaredSymbolInfoKind item) { return (int)item < _lookupTable.Length && _lookupTable[(int)item]; } } } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PatternMatching; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { internal abstract partial class AbstractNavigateToSearchService { private static ImmutableArray<(PatternMatchKind roslynKind, NavigateToMatchKind vsKind)> s_kindPairs = ImmutableArray.Create( (PatternMatchKind.Exact, NavigateToMatchKind.Exact), (PatternMatchKind.Prefix, NavigateToMatchKind.Prefix), (PatternMatchKind.NonLowercaseSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.StartOfWordSubstring, NavigateToMatchKind.Substring), (PatternMatchKind.CamelCaseExact, NavigateToMatchKind.CamelCaseExact), (PatternMatchKind.CamelCasePrefix, NavigateToMatchKind.CamelCasePrefix), (PatternMatchKind.CamelCaseNonContiguousPrefix, NavigateToMatchKind.CamelCaseNonContiguousPrefix), (PatternMatchKind.CamelCaseSubstring, NavigateToMatchKind.CamelCaseSubstring), (PatternMatchKind.CamelCaseNonContiguousSubstring, NavigateToMatchKind.CamelCaseNonContiguousSubstring), (PatternMatchKind.Fuzzy, NavigateToMatchKind.Fuzzy), // Map our value to 'Fuzzy' as that's the lower value the platform supports. (PatternMatchKind.LowercaseSubstring, NavigateToMatchKind.Fuzzy)); public static Task SearchFullyLoadedProjectInCurrentProcessAsync( Project project, ImmutableArray<Document> priorityDocuments, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( project, priorityDocuments, searchDocument: null, pattern: searchPattern, kinds, onResultFound, cancellationToken); } public static Task SearchFullyLoadedDocumentInCurrentProcessAsync( Document document, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { return FindSearchResultsAsync( document.Project, priorityDocuments: ImmutableArray<Document>.Empty, document, searchPattern, kinds, onResultFound, cancellationToken); } private static async Task FindSearchResultsAsync( Project project, ImmutableArray<Document> priorityDocuments, Document? searchDocument, string pattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainerOpt) = PatternMatcher.GetNameAndContainer(pattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); // Prioritize the active documents if we have any. var highPriDocs = priorityDocuments.Where(d => project.ContainsDocument(d.Id)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, highPriDocs, cancellationToken).ConfigureAwait(false); // Then process non-priority documents. var lowPriDocs = project.Documents.Where(d => !highPriDocs.Contains(d)).ToSet(); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, lowPriDocs, cancellationToken).ConfigureAwait(false); // if the caller is only searching a single doc, and we already covered it above, don't bother computing // source-generator docs. if (searchDocument != null && (highPriDocs.Contains(searchDocument) || lowPriDocs.Contains(searchDocument))) return; // Finally, generate and process and source-generated docs. this may take some time, so we always want to // do this after the other documents. var generatedDocs = await project.GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false); await ProcessDocumentsAsync(searchDocument, patternName, patternContainerOpt, declaredSymbolInfoKindsSet, onResultFound, generatedDocs.ToSet<Document>(), cancellationToken).ConfigureAwait(false); } private static async Task ProcessDocumentsAsync( Document? searchDocument, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, ISet<Document> documents, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var document in documents) { if (searchDocument != null && searchDocument != document) continue; cancellationToken.ThrowIfCancellationRequested(); tasks.Add(Task.Run(() => ProcessDocumentAsync(document, patternName, patternContainer, kinds, onResultFound, cancellationToken), cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessDocumentAsync( Document document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(document, cancellationToken).ConfigureAwait(false); await ProcessIndexAsync( document.Id, document, patternName, patternContainer, kinds, onResultFound, index, cancellationToken).ConfigureAwait(false); } public static async Task SearchCachedDocumentsInCurrentProcessAsync( Workspace workspace, ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, string searchPattern, IImmutableSet<string> kinds, Func<RoslynNavigateToItem, Task> onItemFound, CancellationToken cancellationToken) { var stringTable = new StringTable(); var highPriDocsSet = priorityDocumentKeys.ToSet(); var lowPriDocs = documentKeys.WhereAsArray(d => !highPriDocsSet.Contains(d)); // If the user created a dotted pattern then we'll grab the last part of the name var (patternName, patternContainer) = PatternMatcher.GetNameAndContainer(searchPattern); var declaredSymbolInfoKindsSet = new DeclaredSymbolInfoKindSet(kinds); await SearchCachedDocumentsInCurrentProcessAsync( workspace, priorityDocumentKeys, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); await SearchCachedDocumentsInCurrentProcessAsync( workspace, lowPriDocs, patternName, patternContainer, declaredSymbolInfoKindsSet, onItemFound, stringTable, cancellationToken).ConfigureAwait(false); } private static async Task SearchCachedDocumentsInCurrentProcessAsync( Workspace workspace, ImmutableArray<DocumentKey> documentKeys, string patternName, string patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onItemFound, StringTable stringTable, CancellationToken cancellationToken) { using var _ = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var documentKey in documentKeys) { tasks.Add(Task.Run(async () => { var index = await SyntaxTreeIndex.LoadAsync( workspace, documentKey, checksum: null, stringTable, cancellationToken).ConfigureAwait(false); if (index == null) return; await ProcessIndexAsync( documentKey.Id, document: null, patternName, patternContainer, kinds, onItemFound, index, cancellationToken).ConfigureAwait(false); }, cancellationToken)); } await Task.WhenAll(tasks).ConfigureAwait(false); } private static async Task ProcessIndexAsync( DocumentId documentId, Document? document, string patternName, string? patternContainer, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, SyntaxTreeIndex index, CancellationToken cancellationToken) { var containerMatcher = patternContainer != null ? PatternMatcher.CreateDotSeparatedContainerMatcher(patternContainer) : null; using var nameMatcher = PatternMatcher.CreatePatternMatcher(patternName, includeMatchedSpans: true, allowFuzzyMatching: true); using var _1 = containerMatcher; foreach (var declaredSymbolInfo in index.DeclaredSymbolInfos) { // Namespaces are never returned in nav-to as they're too common and have too many locations. if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Namespace) continue; await AddResultIfMatchAsync( documentId, document, declaredSymbolInfo, nameMatcher, containerMatcher, kinds, onResultFound, cancellationToken).ConfigureAwait(false); } } private static async Task AddResultIfMatchAsync( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, PatternMatcher nameMatcher, PatternMatcher? containerMatcher, DeclaredSymbolInfoKindSet kinds, Func<RoslynNavigateToItem, Task> onResultFound, CancellationToken cancellationToken) { using var nameMatches = TemporaryArray<PatternMatch>.Empty; using var containerMatches = TemporaryArray<PatternMatch>.Empty; cancellationToken.ThrowIfCancellationRequested(); if (kinds.Contains(declaredSymbolInfo.Kind) && nameMatcher.AddMatches(declaredSymbolInfo.Name, ref nameMatches.AsRef()) && containerMatcher?.AddMatches(declaredSymbolInfo.FullyQualifiedContainerName, ref containerMatches.AsRef()) != false) { // See if we have a match in a linked file. If so, see if we have the same match in // other projects that this file is linked in. If so, include the full set of projects // the match is in so we can display that well in the UI. // // We can only do this in the case where the solution is loaded and thus we can examine // the relationship between this document and the other documents linked to it. In the // case where the solution isn't fully loaded and we're just reading in cached data, we // don't know what other files we're linked to and can't merge results in this fashion. var additionalMatchingProjects = await GetAdditionalProjectsWithMatchAsync( document, declaredSymbolInfo, cancellationToken).ConfigureAwait(false); var result = ConvertResult( documentId, document, declaredSymbolInfo, nameMatches, containerMatches, additionalMatchingProjects); await onResultFound(result).ConfigureAwait(false); } } private static RoslynNavigateToItem ConvertResult( DocumentId documentId, Document? document, DeclaredSymbolInfo declaredSymbolInfo, in TemporaryArray<PatternMatch> nameMatches, in TemporaryArray<PatternMatch> containerMatches, ImmutableArray<ProjectId> additionalMatchingProjects) { var matchKind = GetNavigateToMatchKind(nameMatches); // A match is considered to be case sensitive if all its constituent pattern matches are // case sensitive. var isCaseSensitive = nameMatches.All(m => m.IsCaseSensitive) && containerMatches.All(m => m.IsCaseSensitive); var kind = GetItemKind(declaredSymbolInfo); using var matchedSpans = TemporaryArray<TextSpan>.Empty; foreach (var match in nameMatches) matchedSpans.AddRange(match.MatchedSpans); // If we were not given a Document instance, then we're finding matches in cached data // and thus could be 'stale'. return new RoslynNavigateToItem( isStale: document == null, documentId, additionalMatchingProjects, declaredSymbolInfo, kind, matchKind, isCaseSensitive, matchedSpans.ToImmutableAndClear()); } private static async ValueTask<ImmutableArray<ProjectId>> GetAdditionalProjectsWithMatchAsync( Document? document, DeclaredSymbolInfo declaredSymbolInfo, CancellationToken cancellationToken) { if (document == null) return ImmutableArray<ProjectId>.Empty; using var _ = ArrayBuilder<ProjectId>.GetInstance(out var result); var solution = document.Project.Solution; var linkedDocumentIds = document.GetLinkedDocumentIds(); foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var index = await SyntaxTreeIndex.GetRequiredIndexAsync(linkedDocument, cancellationToken).ConfigureAwait(false); // See if the index for the other file also contains this same info. If so, merge the results so the // user only sees them as a single hit in the UI. if (index.DeclaredSymbolInfoSet.Contains(declaredSymbolInfo)) result.Add(linkedDocument.Project.Id); } result.RemoveDuplicates(); return result.ToImmutable(); } private static string GetItemKind(DeclaredSymbolInfo declaredSymbolInfo) { switch (declaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: return NavigateToItemKind.Class; case DeclaredSymbolInfoKind.RecordStruct: return NavigateToItemKind.Structure; case DeclaredSymbolInfoKind.Constant: return NavigateToItemKind.Constant; case DeclaredSymbolInfoKind.Delegate: return NavigateToItemKind.Delegate; case DeclaredSymbolInfoKind.Enum: return NavigateToItemKind.Enum; case DeclaredSymbolInfoKind.EnumMember: return NavigateToItemKind.EnumItem; case DeclaredSymbolInfoKind.Event: return NavigateToItemKind.Event; case DeclaredSymbolInfoKind.Field: return NavigateToItemKind.Field; case DeclaredSymbolInfoKind.Interface: return NavigateToItemKind.Interface; case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Method: return NavigateToItemKind.Method; case DeclaredSymbolInfoKind.Module: return NavigateToItemKind.Module; case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Property: return NavigateToItemKind.Property; case DeclaredSymbolInfoKind.Struct: return NavigateToItemKind.Structure; default: throw ExceptionUtilities.UnexpectedValue(declaredSymbolInfo.Kind); } } private static NavigateToMatchKind GetNavigateToMatchKind(in TemporaryArray<PatternMatch> nameMatches) { // work backwards through the match kinds. That way our result is as bad as our worst match part. For // example, say the user searches for `Console.Write` and we find `Console.Write` (exact, exact), and // `Console.WriteLine` (exact, prefix). We don't want the latter hit to be considered an `exact` match, and // thus as good as `Console.Write`. for (var i = s_kindPairs.Length - 1; i >= 0; i--) { var (roslynKind, vsKind) = s_kindPairs[i]; foreach (var match in nameMatches) { if (match.Kind == roslynKind) return vsKind; } } return NavigateToMatchKind.Regular; } private readonly struct DeclaredSymbolInfoKindSet { private readonly ImmutableArray<bool> _lookupTable; public DeclaredSymbolInfoKindSet(IEnumerable<string> navigateToItemKinds) { // The 'Contains' method implementation assumes that the DeclaredSymbolInfoKind type is unsigned. Debug.Assert(Enum.GetUnderlyingType(typeof(DeclaredSymbolInfoKind)) == typeof(byte)); var lookupTable = new bool[Enum.GetValues(typeof(DeclaredSymbolInfoKind)).Length]; foreach (var navigateToItemKind in navigateToItemKinds) { switch (navigateToItemKind) { case NavigateToItemKind.Class: lookupTable[(int)DeclaredSymbolInfoKind.Class] = true; lookupTable[(int)DeclaredSymbolInfoKind.Record] = true; break; case NavigateToItemKind.Constant: lookupTable[(int)DeclaredSymbolInfoKind.Constant] = true; break; case NavigateToItemKind.Delegate: lookupTable[(int)DeclaredSymbolInfoKind.Delegate] = true; break; case NavigateToItemKind.Enum: lookupTable[(int)DeclaredSymbolInfoKind.Enum] = true; break; case NavigateToItemKind.EnumItem: lookupTable[(int)DeclaredSymbolInfoKind.EnumMember] = true; break; case NavigateToItemKind.Event: lookupTable[(int)DeclaredSymbolInfoKind.Event] = true; break; case NavigateToItemKind.Field: lookupTable[(int)DeclaredSymbolInfoKind.Field] = true; break; case NavigateToItemKind.Interface: lookupTable[(int)DeclaredSymbolInfoKind.Interface] = true; break; case NavigateToItemKind.Method: lookupTable[(int)DeclaredSymbolInfoKind.Constructor] = true; lookupTable[(int)DeclaredSymbolInfoKind.ExtensionMethod] = true; lookupTable[(int)DeclaredSymbolInfoKind.Method] = true; break; case NavigateToItemKind.Module: lookupTable[(int)DeclaredSymbolInfoKind.Module] = true; break; case NavigateToItemKind.Property: lookupTable[(int)DeclaredSymbolInfoKind.Indexer] = true; lookupTable[(int)DeclaredSymbolInfoKind.Property] = true; break; case NavigateToItemKind.Structure: lookupTable[(int)DeclaredSymbolInfoKind.Struct] = true; lookupTable[(int)DeclaredSymbolInfoKind.RecordStruct] = true; break; default: // Not a recognized symbol info kind break; } } _lookupTable = ImmutableArray.CreateRange(lookupTable); } public bool Contains(DeclaredSymbolInfoKind item) { return (int)item < _lookupTable.Length && _lookupTable[(int)item]; } } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/CSharp/Portable/FindSymbols/CSharpDeclaredSymbolInfoFactoryService.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.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; protected override NameSyntax GetName(BaseNamespaceDeclarationSyntax node) => node.Name; protected override NameSyntax GetLeft(QualifiedNameSyntax node) => node.Left; protected override NameSyntax GetRight(QualifiedNameSyntax node) => node.Right; protected override SyntaxToken GetIdentifier(IdentifierNameSyntax node) => node.Identifier; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => 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.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.FindSymbols { [ExportLanguageService(typeof(IDeclaredSymbolInfoFactoryService), LanguageNames.CSharp), Shared] internal class CSharpDeclaredSymbolInfoFactoryService : AbstractDeclaredSymbolInfoFactoryService< CompilationUnitSyntax, UsingDirectiveSyntax, BaseNamespaceDeclarationSyntax, TypeDeclarationSyntax, EnumDeclarationSyntax, MemberDeclarationSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDeclaredSymbolInfoFactoryService() { } private static ImmutableArray<string> GetInheritanceNames(StringTable stringTable, BaseListSyntax baseList) { if (baseList == null) { return ImmutableArray<string>.Empty; } var builder = ArrayBuilder<string>.GetInstance(baseList.Types.Count); // It's not sufficient to just store the textual names we see in the inheritance list // of a type. For example if we have: // // using Y = X; // ... // using Z = Y; // ... // class C : Z // // It's insufficient to just state that 'C' derives from 'Z'. If we search for derived // types from 'B' we won't examine 'C'. To solve this, we keep track of the aliasing // that occurs in containing scopes. Then, when we're adding an inheritance name we // walk the alias maps and we also add any names that these names alias to. In the // above example we'd put Z, Y, and X in the inheritance names list for 'C'. // Each dictionary in this list is a mapping from alias name to the name of the thing // it aliases. Then, each scope with alias mapping gets its own entry in this list. // For the above example, we would produce: [{Z => Y}, {Y => X}] var aliasMaps = AllocateAliasMapList(); try { AddAliasMaps(baseList, aliasMaps); foreach (var baseType in baseList.Types) { AddInheritanceName(builder, baseType.Type, aliasMaps); } Intern(stringTable, builder); return builder.ToImmutableAndFree(); } finally { FreeAliasMapList(aliasMaps); } } private static void AddAliasMaps(SyntaxNode node, List<Dictionary<string, string>> aliasMaps) { for (var current = node; current != null; current = current.Parent) { if (current is BaseNamespaceDeclarationSyntax nsDecl) { ProcessUsings(aliasMaps, nsDecl.Usings); } else if (current.IsKind(SyntaxKind.CompilationUnit, out CompilationUnitSyntax compilationUnit)) { ProcessUsings(aliasMaps, compilationUnit.Usings); } } } private static void ProcessUsings(List<Dictionary<string, string>> aliasMaps, SyntaxList<UsingDirectiveSyntax> usings) { Dictionary<string, string> aliasMap = null; foreach (var usingDecl in usings) { if (usingDecl.Alias != null) { var mappedName = GetTypeName(usingDecl.Name); if (mappedName != null) { aliasMap ??= AllocateAliasMap(); // If we have: using X = Goo, then we store a mapping from X -> Goo // here. That way if we see a class that inherits from X we also state // that it inherits from Goo as well. aliasMap[usingDecl.Alias.Name.Identifier.ValueText] = mappedName; } } } if (aliasMap != null) { aliasMaps.Add(aliasMap); } } private static void AddInheritanceName( ArrayBuilder<string> builder, TypeSyntax type, List<Dictionary<string, string>> aliasMaps) { var name = GetTypeName(type); if (name != null) { // First, add the name that the typename that the type directly says it inherits from. builder.Add(name); // Now, walk the alias chain and add any names this alias may eventually map to. var currentName = name; foreach (var aliasMap in aliasMaps) { if (aliasMap.TryGetValue(currentName, out var mappedName)) { // Looks like this could be an alias. Also include the name the alias points to builder.Add(mappedName); // Keep on searching. An alias in an inner namespcae can refer to an // alias in an outer namespace. currentName = mappedName; } } } } protected override void AddDeclaredSymbolInfosWorker( SyntaxNode container, MemberDeclarationSyntax node, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { // If this is a part of partial type that only contains nested types, then we don't make an info type for // it. That's because we effectively think of this as just being a virtual container just to hold the nested // types, and not something someone would want to explicitly navigate to itself. Similar to how we think of // namespaces. if (node is TypeDeclarationSyntax typeDeclaration && typeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword) && typeDeclaration.Members.Any() && typeDeclaration.Members.All(m => m is BaseTypeDeclarationSyntax)) { return; } switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.Identifier.ValueText, GetTypeParameterSuffix(typeDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeDecl.Modifiers.Any(SyntaxKind.PartialKeyword), node.Kind() switch { SyntaxKind.ClassDeclaration => DeclaredSymbolInfoKind.Class, SyntaxKind.RecordDeclaration => DeclaredSymbolInfoKind.Record, SyntaxKind.InterfaceDeclaration => DeclaredSymbolInfoKind.Interface, SyntaxKind.StructDeclaration => DeclaredSymbolInfoKind.Struct, SyntaxKind.RecordStructDeclaration => DeclaredSymbolInfoKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }, GetAccessibility(container, typeDecl.Modifiers), typeDecl.Identifier.Span, GetInheritanceNames(stringTable, typeDecl.BaseList), IsNestedType(typeDecl))); return; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl.Modifiers), enumDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, isNestedType: IsNestedType(enumDecl))); return; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, ctorDecl.Identifier.ValueText, GetConstructorSuffix(ctorDecl), containerDisplayName, fullyQualifiedContainerName, ctorDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, ctorDecl.Modifiers), ctorDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: ctorDecl.ParameterList?.Parameters.Count ?? 0)); return; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl.Modifiers), delegateDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, enumMember.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl.Modifiers), eventDecl.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, "this", GetIndexerSuffix(indexerDecl), containerDisplayName, fullyQualifiedContainerName, indexerDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Indexer, GetAccessibility(container, indexerDecl.Modifiers), indexerDecl.ThisKeyword.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; var isExtensionMethod = IsExtensionMethod(method); declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, method.Identifier.ValueText, GetMethodSuffix(method), containerDisplayName, fullyQualifiedContainerName, method.Modifiers.Any(SyntaxKind.PartialKeyword), isExtensionMethod ? DeclaredSymbolInfoKind.ExtensionMethod : DeclaredSymbolInfoKind.Method, GetAccessibility(container, method.Modifiers), method.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty, parameterCount: method.ParameterList?.Parameters.Count ?? 0, typeParameterCount: method.TypeParameterList?.Parameters.Count ?? 0)); if (isExtensionMethod) AddExtensionMethodInfo(method, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo); return; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, property.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, property.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, property.Modifiers), property.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); return; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, variableDeclarator.Identifier.ValueText, null, containerDisplayName, fullyQualifiedContainerName, fieldDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword), kind, GetAccessibility(container, fieldDeclaration.Modifiers), variableDeclarator.Identifier.Span, inheritanceNames: ImmutableArray<string>.Empty)); } return; } } protected override SyntaxList<MemberDeclarationSyntax> GetChildren(CompilationUnitSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(BaseNamespaceDeclarationSyntax node) => node.Members; protected override SyntaxList<MemberDeclarationSyntax> GetChildren(TypeDeclarationSyntax node) => node.Members; protected override IEnumerable<MemberDeclarationSyntax> GetChildren(EnumDeclarationSyntax node) => node.Members; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(CompilationUnitSyntax node) => node.Usings; protected override SyntaxList<UsingDirectiveSyntax> GetUsingAliases(BaseNamespaceDeclarationSyntax node) => node.Usings; protected override NameSyntax GetName(BaseNamespaceDeclarationSyntax node) => node.Name; protected override NameSyntax GetLeft(QualifiedNameSyntax node) => node.Left; protected override NameSyntax GetRight(QualifiedNameSyntax node) => node.Right; protected override SyntaxToken GetIdentifier(IdentifierNameSyntax node) => node.Identifier; private static bool IsNestedType(BaseTypeDeclarationSyntax typeDecl) => typeDecl.Parent is BaseTypeDeclarationSyntax; private static string GetConstructorSuffix(ConstructorDeclarationSyntax constructor) => constructor.Modifiers.Any(SyntaxKind.StaticKeyword) ? ".static " + constructor.Identifier + "()" : GetSuffix('(', ')', constructor.ParameterList.Parameters); private static string GetMethodSuffix(MethodDeclarationSyntax method) => GetTypeParameterSuffix(method.TypeParameterList) + GetSuffix('(', ')', method.ParameterList.Parameters); private static string GetIndexerSuffix(IndexerDeclarationSyntax indexer) => GetSuffix('[', ']', indexer.ParameterList.Parameters); private static string GetTypeParameterSuffix(TypeParameterListSyntax typeParameterList) { if (typeParameterList == null) { return null; } var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append('<'); var first = true; foreach (var parameter in typeParameterList.Parameters) { if (!first) { builder.Append(", "); } builder.Append(parameter.Identifier.Text); first = false; } builder.Append('>'); return pooledBuilder.ToStringAndFree(); } /// <summary> /// Builds up the suffix to show for something with parameters in navigate-to. /// While it would be nice to just use the compiler SymbolDisplay API for this, /// it would be too expensive as it requires going back to Symbols (which requires /// creating compilations, etc.) in a perf sensitive area. /// /// So, instead, we just build a reasonable suffix using the pure syntax that a /// user provided. That means that if they wrote "Method(System.Int32 i)" we'll /// show that as "Method(System.Int32)" not "Method(int)". Given that this is /// actually what the user wrote, and it saves us from ever having to go back to /// symbols/compilations, this is well worth it, even if it does mean we have to /// create our own 'symbol display' logic here. /// </summary> private static string GetSuffix( char openBrace, char closeBrace, SeparatedSyntaxList<ParameterSyntax> parameters) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append(openBrace); AppendParameters(parameters, builder); builder.Append(closeBrace); return pooledBuilder.ToStringAndFree(); } private static void AppendParameters(SeparatedSyntaxList<ParameterSyntax> parameters, StringBuilder builder) { var first = true; foreach (var parameter in parameters) { if (!first) { builder.Append(", "); } foreach (var modifier in parameter.Modifiers) { builder.Append(modifier.Text); builder.Append(' '); } if (parameter.Type != null) { AppendTokens(parameter.Type, builder); } else { builder.Append(parameter.Identifier.Text); } first = false; } } protected override string GetContainerDisplayName(MemberDeclarationSyntax node) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); protected override string GetFullyQualifiedContainerName(MemberDeclarationSyntax node, string rootNamespace) => CSharpSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); private static Accessibility GetAccessibility(SyntaxNode container, SyntaxTokenList modifiers) { var sawInternal = false; foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: sawInternal = true; continue; } } if (sawInternal) return Accessibility.Internal; // No accessibility modifiers: switch (container.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: // Anything without modifiers is private if it's in a class/struct declaration. return Accessibility.Private; case SyntaxKind.InterfaceDeclaration: // Anything without modifiers is public if it's in an interface declaration. return Accessibility.Public; case SyntaxKind.CompilationUnit: // Things are private by default in script if (((CSharpParseOptions)container.SyntaxTree.Options).Kind == SourceCodeKind.Script) return Accessibility.Private; return Accessibility.Internal; default: // Otherwise it's internal return Accessibility.Internal; } } private static string GetTypeName(TypeSyntax type) { if (type is SimpleNameSyntax simpleName) { return GetSimpleTypeName(simpleName); } else if (type is QualifiedNameSyntax qualifiedName) { return GetSimpleTypeName(qualifiedName.Right); } else if (type is AliasQualifiedNameSyntax aliasName) { return GetSimpleTypeName(aliasName.Name); } return null; } private static string GetSimpleTypeName(SimpleNameSyntax name) => name.Identifier.ValueText; private static bool IsExtensionMethod(MethodDeclarationSyntax method) => method.ParameterList.Parameters.Count > 0 && method.ParameterList.Parameters[0].Modifiers.Any(SyntaxKind.ThisKeyword); // Root namespace is a VB only concept, which basically means root namespace is always global in C#. protected override string GetRootNamespace(CompilationOptions compilationOptions) => string.Empty; protected override bool TryGetAliasesFromUsingDirective( UsingDirectiveSyntax usingDirectiveNode, out ImmutableArray<(string aliasName, string name)> aliases) { if (usingDirectiveNode.Alias != null) { if (TryGetSimpleTypeName(usingDirectiveNode.Alias.Name, typeParameterNames: null, out var aliasName, out _) && TryGetSimpleTypeName(usingDirectiveNode.Name, typeParameterNames: null, out var name, out _)) { aliases = ImmutableArray.Create<(string, string)>((aliasName, name)); return true; } } aliases = default; return false; } protected override string GetReceiverTypeName(MemberDeclarationSyntax node) { var methodDeclaration = (MethodDeclarationSyntax)node; Debug.Assert(IsExtensionMethod(methodDeclaration)); var typeParameterNames = methodDeclaration.TypeParameterList?.Parameters.SelectAsArray(p => p.Identifier.Text); TryGetSimpleTypeName(methodDeclaration.ParameterList.Parameters[0].Type, typeParameterNames, out var targetTypeName, out var isArray); return CreateReceiverTypeString(targetTypeName, isArray); } private static bool TryGetSimpleTypeName(SyntaxNode node, ImmutableArray<string>? typeParameterNames, out string simpleTypeName, out bool isArray) { isArray = false; if (node is TypeSyntax typeNode) { switch (typeNode) { case IdentifierNameSyntax identifierNameNode: // We consider it a complex method if the receiver type is a type parameter. var text = identifierNameNode.Identifier.Text; simpleTypeName = typeParameterNames?.Contains(text) == true ? null : text; return simpleTypeName != null; case ArrayTypeSyntax arrayTypeNode: isArray = true; return TryGetSimpleTypeName(arrayTypeNode.ElementType, typeParameterNames, out simpleTypeName, out _); case GenericNameSyntax genericNameNode: var name = genericNameNode.Identifier.Text; var arity = genericNameNode.Arity; simpleTypeName = arity == 0 ? name : name + ArityUtilities.GetMetadataAritySuffix(arity); return true; case PredefinedTypeSyntax predefinedTypeNode: simpleTypeName = GetSpecialTypeName(predefinedTypeNode); return simpleTypeName != null; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return TryGetSimpleTypeName(aliasQualifiedNameNode.Name, typeParameterNames, out simpleTypeName, out _); case QualifiedNameSyntax qualifiedNameNode: // For an identifier to the right of a '.', it can't be a type parameter, // so we don't need to check for it further. return TryGetSimpleTypeName(qualifiedNameNode.Right, typeParameterNames: null, out simpleTypeName, out _); case NullableTypeSyntax nullableNode: // Ignore nullability, becase nullable reference type might not be enabled universally. // In the worst case we just include more methods to check in out filter. return TryGetSimpleTypeName(nullableNode.ElementType, typeParameterNames, out simpleTypeName, out isArray); case TupleTypeSyntax tupleType: simpleTypeName = CreateValueTupleTypeString(tupleType.Elements.Count); return true; } } simpleTypeName = null; return false; } private static string GetSpecialTypeName(PredefinedTypeSyntax predefinedTypeNode) { var kind = predefinedTypeNode.Keyword.Kind(); return kind switch { SyntaxKind.BoolKeyword => "Boolean", SyntaxKind.ByteKeyword => "Byte", SyntaxKind.SByteKeyword => "SByte", SyntaxKind.ShortKeyword => "Int16", SyntaxKind.UShortKeyword => "UInt16", SyntaxKind.IntKeyword => "Int32", SyntaxKind.UIntKeyword => "UInt32", SyntaxKind.LongKeyword => "Int64", SyntaxKind.ULongKeyword => "UInt64", SyntaxKind.DoubleKeyword => "Double", SyntaxKind.FloatKeyword => "Single", SyntaxKind.DecimalKeyword => "Decimal", SyntaxKind.StringKeyword => "String", SyntaxKind.CharKeyword => "Char", SyntaxKind.ObjectKeyword => "Object", _ => null, }; } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/FindSymbols/Declarations/DeclarationFinder.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal static partial class DeclarationFinder { private static Task AddCompilationDeclarationsWithNormalQueryAsync( Project project, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, CancellationToken cancellationToken) { Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); return AddCompilationDeclarationsWithNormalQueryAsync( project, query, filter, list, startingCompilation: null, startingAssembly: null, cancellationToken: cancellationToken); } private static async Task AddCompilationDeclarationsWithNormalQueryAsync( Project project, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, Compilation startingCompilation, IAssemblySymbol startingAssembly, CancellationToken cancellationToken) { if (!project.SupportsCompilation) return; Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); using (Logger.LogBlock(FunctionId.SymbolFinder_Project_AddDeclarationsAsync, cancellationToken)) { var syntaxFacts = project.LanguageServices.GetService<ISyntaxFactsService>(); // If this is an exact query, we can speed things up by just calling into the // compilation entrypoints that take a string directly. // // the search is 'exact' if it's either an exact-case-sensitive search, // or it's an exact-case-insensitive search and we're in a case-insensitive // language. var isExactNameSearch = query.Kind == SearchKind.Exact || (query.Kind == SearchKind.ExactIgnoreCase && !syntaxFacts.IsCaseSensitive); // Do a quick syntactic check first using our cheaply built indices. That will help us avoid creating // a compilation here if it's not necessary. In the case of an exact name search we can call a special // overload that quickly uses the direct bloom-filter identifier maps in the index. If it's nto an // exact name search, then we will run the query's predicate over every DeclaredSymbolInfo stored in // the doc. var containsSymbol = isExactNameSearch ? await project.ContainsSymbolsWithNameAsync(query.Name, cancellationToken).ConfigureAwait(false) : await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false); if (!containsSymbol) return; var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = isExactNameSearch ? compilation.GetSymbolsWithName(query.Name, filter, cancellationToken) : compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken); var symbolsWithName = symbols.ToImmutableArray(); if (startingCompilation != null && startingAssembly != null && !Equals(compilation.Assembly, startingAssembly)) { // Return symbols from skeleton assembly in this case so that symbols have // the same language as startingCompilation. symbolsWithName = symbolsWithName.Select(s => s.GetSymbolKey(cancellationToken).Resolve(startingCompilation, cancellationToken: cancellationToken).Symbol) .WhereNotNull() .ToImmutableArray(); } list.AddRange(FilterByCriteria(symbolsWithName, filter)); } } private static async Task AddMetadataDeclarationsWithNormalQueryAsync( Project project, IAssemblySymbol assembly, PortableExecutableReference referenceOpt, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, CancellationToken cancellationToken) { // All entrypoints to this function are Find functions that are only searching // for specific strings (i.e. they never do a custom search). Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); using (Logger.LogBlock(FunctionId.SymbolFinder_Assembly_AddDeclarationsAsync, cancellationToken)) { if (referenceOpt != null) { var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( project.Solution, referenceOpt, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); var symbols = await info.FindAsync( query, assembly, filter, cancellationToken).ConfigureAwait(false); list.AddRange(symbols); } } } internal static ImmutableArray<ISymbol> FilterByCriteria(ImmutableArray<ISymbol> symbols, SymbolFilter criteria) => symbols.WhereAsArray(s => MeetCriteria(s, criteria)); private static bool MeetCriteria(ISymbol symbol, SymbolFilter filter) { if (!symbol.IsImplicitlyDeclared && !symbol.IsAccessor()) { if (IsOn(filter, SymbolFilter.Namespace) && symbol.Kind == SymbolKind.Namespace) { return true; } if (IsOn(filter, SymbolFilter.Type) && symbol is ITypeSymbol) { return true; } if (IsOn(filter, SymbolFilter.Member) && IsNonTypeMember(symbol)) { return true; } } return false; } private static bool IsNonTypeMember(ISymbol symbol) { return symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field; } private static bool IsOn(SymbolFilter filter, SymbolFilter flag) => (filter & flag) == flag; } }
// 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal static partial class DeclarationFinder { private static Task AddCompilationDeclarationsWithNormalQueryAsync( Project project, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, CancellationToken cancellationToken) { Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); return AddCompilationDeclarationsWithNormalQueryAsync( project, query, filter, list, startingCompilation: null, startingAssembly: null, cancellationToken: cancellationToken); } private static async Task AddCompilationDeclarationsWithNormalQueryAsync( Project project, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, Compilation startingCompilation, IAssemblySymbol startingAssembly, CancellationToken cancellationToken) { if (!project.SupportsCompilation) return; Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); using (Logger.LogBlock(FunctionId.SymbolFinder_Project_AddDeclarationsAsync, cancellationToken)) { var syntaxFacts = project.LanguageServices.GetService<ISyntaxFactsService>(); // If this is an exact query, we can speed things up by just calling into the // compilation entrypoints that take a string directly. // // the search is 'exact' if it's either an exact-case-sensitive search, // or it's an exact-case-insensitive search and we're in a case-insensitive // language. var isExactNameSearch = query.Kind == SearchKind.Exact || (query.Kind == SearchKind.ExactIgnoreCase && !syntaxFacts.IsCaseSensitive); // Do a quick syntactic check first using our cheaply built indices. That will help us avoid creating // a compilation here if it's not necessary. In the case of an exact name search we can call a special // overload that quickly uses the direct bloom-filter identifier maps in the index. If it's nto an // exact name search, then we will run the query's predicate over every DeclaredSymbolInfo stored in // the doc. var containsSymbol = isExactNameSearch ? await project.ContainsSymbolsWithNameAsync(query.Name, cancellationToken).ConfigureAwait(false) : await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false); if (!containsSymbol) return; var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var symbols = isExactNameSearch ? compilation.GetSymbolsWithName(query.Name, filter, cancellationToken) : compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken); var symbolsWithName = symbols.ToImmutableArray(); if (startingCompilation != null && startingAssembly != null && !Equals(compilation.Assembly, startingAssembly)) { // Return symbols from skeleton assembly in this case so that symbols have // the same language as startingCompilation. symbolsWithName = symbolsWithName.Select(s => s.GetSymbolKey(cancellationToken).Resolve(startingCompilation, cancellationToken: cancellationToken).Symbol) .WhereNotNull() .ToImmutableArray(); } list.AddRange(FilterByCriteria(symbolsWithName, filter)); } } private static async Task AddMetadataDeclarationsWithNormalQueryAsync( Project project, IAssemblySymbol assembly, PortableExecutableReference referenceOpt, SearchQuery query, SymbolFilter filter, ArrayBuilder<ISymbol> list, CancellationToken cancellationToken) { // All entrypoints to this function are Find functions that are only searching // for specific strings (i.e. they never do a custom search). Contract.ThrowIfTrue(query.Kind == SearchKind.Custom, "Custom queries are not supported in this API"); using (Logger.LogBlock(FunctionId.SymbolFinder_Assembly_AddDeclarationsAsync, cancellationToken)) { if (referenceOpt != null) { var info = await SymbolTreeInfo.GetInfoForMetadataReferenceAsync( project.Solution, referenceOpt, loadOnly: false, cancellationToken: cancellationToken).ConfigureAwait(false); var symbols = await info.FindAsync( query, assembly, filter, cancellationToken).ConfigureAwait(false); list.AddRange(symbols); } } } internal static ImmutableArray<ISymbol> FilterByCriteria(ImmutableArray<ISymbol> symbols, SymbolFilter criteria) => symbols.WhereAsArray(s => MeetCriteria(s, criteria)); private static bool MeetCriteria(ISymbol symbol, SymbolFilter filter) { if (!symbol.IsImplicitlyDeclared && !symbol.IsAccessor()) { if (IsOn(filter, SymbolFilter.Namespace) && symbol.Kind == SymbolKind.Namespace) { return true; } if (IsOn(filter, SymbolFilter.Type) && symbol is ITypeSymbol) { return true; } if (IsOn(filter, SymbolFilter.Member) && IsNonTypeMember(symbol)) { return true; } } return false; } private static bool IsNonTypeMember(ISymbol symbol) { return symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field; } private static bool IsOn(SymbolFilter filter, SymbolFilter flag) => (filter & flag) == flag; } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/FindSymbols/DeclaredSymbolInfo.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.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal enum DeclaredSymbolInfoKind : byte { Class, Constant, Constructor, Delegate, Enum, EnumMember, Event, ExtensionMethod, Field, Indexer, Interface, Method, Module, Namespace, Property, Record, RecordStruct, Struct, } [DataContract] internal readonly struct DeclaredSymbolInfo : IEquatable<DeclaredSymbolInfo> { /// <summary> /// The name to pattern match against, and to show in a final presentation layer. /// </summary> [DataMember(Order = 0)] public readonly string Name; /// <summary> /// An optional suffix to be shown in a presentation layer appended to <see cref="Name"/>. /// Can be null. /// </summary> [DataMember(Order = 1)] public readonly string NameSuffix; /// <summary> /// Container of the symbol that can be shown in a final presentation layer. /// For example, the container of a type "KeyValuePair" might be /// "System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;". This can /// then be shown with something like "type System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;" /// to indicate where the symbol is located. /// </summary> [DataMember(Order = 2)] public readonly string ContainerDisplayName; /// <summary> /// Dotted container name of the symbol, used for pattern matching. For example /// The fully qualified container of a type "KeyValuePair" would be /// "System.Collections.Generic.Dictionary" (note the lack of type parameters). /// This way someone can search for "D.KVP" and have the "D" part of the pattern /// match against this. This should not be shown in a presentation layer. /// </summary> [DataMember(Order = 3)] public readonly string FullyQualifiedContainerName; [DataMember(Order = 4)] public readonly TextSpan Span; /// <summary> /// The names directly referenced in source that this type inherits from. /// </summary> [DataMember(Order = 5)] public ImmutableArray<string> InheritanceNames { get; } // Store the kind (5 bits), accessibility (4 bits), parameter-count (4 bits), and type-parameter-count (4 bits) // in a single int. [DataMember(Order = 6)] private readonly uint _flags; private const uint Lower4BitMask = 0b1111; private const uint Lower5BitMask = 0b11111; public DeclaredSymbolInfoKind Kind => GetKind(_flags); public Accessibility Accessibility => GetAccessibility(_flags); public byte ParameterCount => GetParameterCount(_flags); public byte TypeParameterCount => GetTypeParameterCount(_flags); public bool IsNestedType => GetIsNestedType(_flags); public bool IsPartial => GetIsPartial(_flags); [Obsolete("Do not call directly. Only around for serialization. Use Create instead")] public DeclaredSymbolInfo( string name, string nameSuffix, string containerDisplayName, string fullyQualifiedContainerName, TextSpan span, ImmutableArray<string> inheritanceNames, uint flags) { Name = name; NameSuffix = nameSuffix; ContainerDisplayName = containerDisplayName; FullyQualifiedContainerName = fullyQualifiedContainerName; Span = span; InheritanceNames = inheritanceNames; _flags = flags; } public static DeclaredSymbolInfo Create( StringTable stringTable, string name, string nameSuffix, string containerDisplayName, string fullyQualifiedContainerName, bool isPartial, DeclaredSymbolInfoKind kind, Accessibility accessibility, TextSpan span, ImmutableArray<string> inheritanceNames, bool isNestedType = false, int parameterCount = 0, int typeParameterCount = 0) { // Max value that we can store depending on how many bits we have to store that particular value in. const uint Max5BitValue = 0b11111; const uint Max4BitValue = 0b1111; Contract.ThrowIfTrue((uint)accessibility > Max4BitValue); Contract.ThrowIfTrue((uint)kind > Max5BitValue); parameterCount = Math.Min(parameterCount, (byte)Max4BitValue); typeParameterCount = Math.Min(typeParameterCount, (byte)Max4BitValue); var flags = (uint)kind | ((uint)accessibility << 5) | ((uint)parameterCount << 9) | ((uint)typeParameterCount << 13) | ((isNestedType ? 1u : 0u) << 17) | ((isPartial ? 1u : 0u) << 18); #pragma warning disable CS0618 // Type or member is obsolete return new DeclaredSymbolInfo( Intern(stringTable, name), Intern(stringTable, nameSuffix), Intern(stringTable, containerDisplayName), Intern(stringTable, fullyQualifiedContainerName), span, inheritanceNames, flags); #pragma warning restore CS0618 // Type or member is obsolete } [return: NotNullIfNotNull("name")] public static string? Intern(StringTable stringTable, string? name) => name == null ? null : stringTable.Add(name); private static DeclaredSymbolInfoKind GetKind(uint flags) => (DeclaredSymbolInfoKind)(flags & Lower5BitMask); private static Accessibility GetAccessibility(uint flags) => (Accessibility)((flags >> 5) & Lower4BitMask); private static byte GetParameterCount(uint flags) => (byte)((flags >> 9) & Lower4BitMask); private static byte GetTypeParameterCount(uint flags) => (byte)((flags >> 13) & Lower4BitMask); private static bool GetIsNestedType(uint flags) => ((flags >> 17) & 1) == 1; private static bool GetIsPartial(uint flags) => ((flags >> 18) & 1) == 1; internal void WriteTo(ObjectWriter writer) { writer.WriteString(Name); writer.WriteString(NameSuffix); writer.WriteString(ContainerDisplayName); writer.WriteString(FullyQualifiedContainerName); writer.WriteUInt32(_flags); writer.WriteInt32(Span.Start); writer.WriteInt32(Span.Length); writer.WriteInt32(InheritanceNames.Length); foreach (var name in InheritanceNames) writer.WriteString(name); } internal static DeclaredSymbolInfo ReadFrom_ThrowsOnFailure(StringTable stringTable, ObjectReader reader) { var name = reader.ReadString(); var nameSuffix = reader.ReadString(); var containerDisplayName = reader.ReadString(); var fullyQualifiedContainerName = reader.ReadString(); var flags = reader.ReadUInt32(); var spanStart = reader.ReadInt32(); var spanLength = reader.ReadInt32(); var inheritanceNamesLength = reader.ReadInt32(); var builder = ArrayBuilder<string>.GetInstance(inheritanceNamesLength); for (var i = 0; i < inheritanceNamesLength; i++) builder.Add(reader.ReadString()); var span = new TextSpan(spanStart, spanLength); return Create( stringTable, name: name, nameSuffix: nameSuffix, containerDisplayName: containerDisplayName, fullyQualifiedContainerName: fullyQualifiedContainerName, isPartial: GetIsPartial(flags), kind: GetKind(flags), accessibility: GetAccessibility(flags), span: span, inheritanceNames: builder.ToImmutableAndFree(), parameterCount: GetParameterCount(flags), typeParameterCount: GetTypeParameterCount(flags)); } public ISymbol? TryResolve(SemanticModel semanticModel, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); if (root.FullSpan.Contains(this.Span)) { var node = root.FindNode(this.Span); return semanticModel.GetDeclaredSymbol(node, cancellationToken); } else { var message = $@"Invalid span in {nameof(DeclaredSymbolInfo)}. {nameof(this.Span)} = {this.Span} {nameof(root.FullSpan)} = {root.FullSpan}"; FatalError.ReportAndCatch(new InvalidOperationException(message)); return null; } } public override bool Equals(object? obj) => obj is DeclaredSymbolInfo info && Equals(info); public bool Equals(DeclaredSymbolInfo other) => Name == other.Name && NameSuffix == other.NameSuffix && ContainerDisplayName == other.ContainerDisplayName && FullyQualifiedContainerName == other.FullyQualifiedContainerName && Span.Equals(other.Span) && _flags == other._flags && InheritanceNames.SequenceEqual(other.InheritanceNames, arg: true, (s1, s2, _) => s1 == s2); public override int GetHashCode() => Hash.Combine(Name, Hash.Combine(NameSuffix, Hash.Combine(ContainerDisplayName, Hash.Combine(FullyQualifiedContainerName, Hash.Combine(Span.GetHashCode(), Hash.Combine((int)_flags, Hash.CombineValues(InheritanceNames))))))); } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal enum DeclaredSymbolInfoKind : byte { Class, Constant, Constructor, Delegate, Enum, EnumMember, Event, ExtensionMethod, Field, Indexer, Interface, Method, Module, Namespace, Property, Record, RecordStruct, Struct, } [DataContract] internal readonly struct DeclaredSymbolInfo : IEquatable<DeclaredSymbolInfo> { /// <summary> /// The name to pattern match against, and to show in a final presentation layer. /// </summary> [DataMember(Order = 0)] public readonly string Name; /// <summary> /// An optional suffix to be shown in a presentation layer appended to <see cref="Name"/>. /// Can be null. /// </summary> [DataMember(Order = 1)] public readonly string NameSuffix; /// <summary> /// Container of the symbol that can be shown in a final presentation layer. /// For example, the container of a type "KeyValuePair" might be /// "System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;". This can /// then be shown with something like "type System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;" /// to indicate where the symbol is located. /// </summary> [DataMember(Order = 2)] public readonly string ContainerDisplayName; /// <summary> /// Dotted container name of the symbol, used for pattern matching. For example /// The fully qualified container of a type "KeyValuePair" would be /// "System.Collections.Generic.Dictionary" (note the lack of type parameters). /// This way someone can search for "D.KVP" and have the "D" part of the pattern /// match against this. This should not be shown in a presentation layer. /// </summary> [DataMember(Order = 3)] public readonly string FullyQualifiedContainerName; [DataMember(Order = 4)] public readonly TextSpan Span; /// <summary> /// The names directly referenced in source that this type inherits from. /// </summary> [DataMember(Order = 5)] public ImmutableArray<string> InheritanceNames { get; } // Store the kind (5 bits), accessibility (4 bits), parameter-count (4 bits), and type-parameter-count (4 bits) // in a single int. [DataMember(Order = 6)] private readonly uint _flags; private const uint Lower4BitMask = 0b1111; private const uint Lower5BitMask = 0b11111; public DeclaredSymbolInfoKind Kind => GetKind(_flags); public Accessibility Accessibility => GetAccessibility(_flags); public byte ParameterCount => GetParameterCount(_flags); public byte TypeParameterCount => GetTypeParameterCount(_flags); public bool IsNestedType => GetIsNestedType(_flags); public bool IsPartial => GetIsPartial(_flags); [Obsolete("Do not call directly. Only around for serialization. Use Create instead")] public DeclaredSymbolInfo( string name, string nameSuffix, string containerDisplayName, string fullyQualifiedContainerName, TextSpan span, ImmutableArray<string> inheritanceNames, uint flags) { Name = name; NameSuffix = nameSuffix; ContainerDisplayName = containerDisplayName; FullyQualifiedContainerName = fullyQualifiedContainerName; Span = span; InheritanceNames = inheritanceNames; _flags = flags; } public static DeclaredSymbolInfo Create( StringTable stringTable, string name, string nameSuffix, string containerDisplayName, string fullyQualifiedContainerName, bool isPartial, DeclaredSymbolInfoKind kind, Accessibility accessibility, TextSpan span, ImmutableArray<string> inheritanceNames, bool isNestedType = false, int parameterCount = 0, int typeParameterCount = 0) { // Max value that we can store depending on how many bits we have to store that particular value in. const uint Max5BitValue = 0b11111; const uint Max4BitValue = 0b1111; Contract.ThrowIfTrue((uint)accessibility > Max4BitValue); Contract.ThrowIfTrue((uint)kind > Max5BitValue); parameterCount = Math.Min(parameterCount, (byte)Max4BitValue); typeParameterCount = Math.Min(typeParameterCount, (byte)Max4BitValue); var flags = (uint)kind | ((uint)accessibility << 5) | ((uint)parameterCount << 9) | ((uint)typeParameterCount << 13) | ((isNestedType ? 1u : 0u) << 17) | ((isPartial ? 1u : 0u) << 18); #pragma warning disable CS0618 // Type or member is obsolete return new DeclaredSymbolInfo( Intern(stringTable, name), Intern(stringTable, nameSuffix), Intern(stringTable, containerDisplayName), Intern(stringTable, fullyQualifiedContainerName), span, inheritanceNames, flags); #pragma warning restore CS0618 // Type or member is obsolete } [return: NotNullIfNotNull("name")] public static string? Intern(StringTable stringTable, string? name) => name == null ? null : stringTable.Add(name); private static DeclaredSymbolInfoKind GetKind(uint flags) => (DeclaredSymbolInfoKind)(flags & Lower5BitMask); private static Accessibility GetAccessibility(uint flags) => (Accessibility)((flags >> 5) & Lower4BitMask); private static byte GetParameterCount(uint flags) => (byte)((flags >> 9) & Lower4BitMask); private static byte GetTypeParameterCount(uint flags) => (byte)((flags >> 13) & Lower4BitMask); private static bool GetIsNestedType(uint flags) => ((flags >> 17) & 1) == 1; private static bool GetIsPartial(uint flags) => ((flags >> 18) & 1) == 1; internal void WriteTo(ObjectWriter writer) { writer.WriteString(Name); writer.WriteString(NameSuffix); writer.WriteString(ContainerDisplayName); writer.WriteString(FullyQualifiedContainerName); writer.WriteUInt32(_flags); writer.WriteInt32(Span.Start); writer.WriteInt32(Span.Length); writer.WriteInt32(InheritanceNames.Length); foreach (var name in InheritanceNames) writer.WriteString(name); } internal static DeclaredSymbolInfo ReadFrom_ThrowsOnFailure(StringTable stringTable, ObjectReader reader) { var name = reader.ReadString(); var nameSuffix = reader.ReadString(); var containerDisplayName = reader.ReadString(); var fullyQualifiedContainerName = reader.ReadString(); var flags = reader.ReadUInt32(); var spanStart = reader.ReadInt32(); var spanLength = reader.ReadInt32(); var inheritanceNamesLength = reader.ReadInt32(); var builder = ArrayBuilder<string>.GetInstance(inheritanceNamesLength); for (var i = 0; i < inheritanceNamesLength; i++) builder.Add(reader.ReadString()); var span = new TextSpan(spanStart, spanLength); return Create( stringTable, name: name, nameSuffix: nameSuffix, containerDisplayName: containerDisplayName, fullyQualifiedContainerName: fullyQualifiedContainerName, isPartial: GetIsPartial(flags), kind: GetKind(flags), accessibility: GetAccessibility(flags), span: span, inheritanceNames: builder.ToImmutableAndFree(), parameterCount: GetParameterCount(flags), typeParameterCount: GetTypeParameterCount(flags)); } public ISymbol? TryResolve(SemanticModel semanticModel, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); if (root.FullSpan.Contains(this.Span)) { var node = root.FindNode(this.Span); return semanticModel.GetDeclaredSymbol(node, cancellationToken); } else { var message = $@"Invalid span in {nameof(DeclaredSymbolInfo)}. {nameof(this.Span)} = {this.Span} {nameof(root.FullSpan)} = {root.FullSpan}"; FatalError.ReportAndCatch(new InvalidOperationException(message)); return null; } } public override bool Equals(object? obj) => obj is DeclaredSymbolInfo info && Equals(info); public bool Equals(DeclaredSymbolInfo other) => Name == other.Name && NameSuffix == other.NameSuffix && ContainerDisplayName == other.ContainerDisplayName && FullyQualifiedContainerName == other.FullyQualifiedContainerName && Span.Equals(other.Span) && _flags == other._flags && InheritanceNames.SequenceEqual(other.InheritanceNames, arg: true, (s1, s2, _) => s1 == s2); public override int GetHashCode() => Hash.Combine(Name, Hash.Combine(NameSuffix, Hash.Combine(ContainerDisplayName, Hash.Combine(FullyQualifiedContainerName, Hash.Combine(Span.GetHashCode(), Hash.Combine((int)_flags, Hash.CombineValues(InheritanceNames))))))); } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Persistence.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class SyntaxTreeIndex : IObjectWritable { private const string PersistenceName = "<SyntaxTreeIndex>"; private static readonly Checksum SerializationFormatChecksum = Checksum.Create("23"); public readonly Checksum? Checksum; private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken) => LoadAsync(document.Project.Solution.Workspace, DocumentKey.ToDocumentKey(document), checksum, GetStringTable(document.Project), cancellationToken); public static async Task<SyntaxTreeIndex?> LoadAsync( Workspace workspace, DocumentKey documentKey, Checksum? checksum, StringTable stringTable, CancellationToken cancellationToken) { try { var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetRequiredService<IPersistentStorageService>(); var storage = await persistentStorageService.GetStorageAsync( workspace, documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // attempt to load from persisted state using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader != null) return ReadFrom(stringTable, reader, checksum); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return null; } public static async Task<Checksum> GetChecksumAsync( Document document, CancellationToken cancellationToken) { // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change // any time the SyntaxTree could have changed. Right now, that can only happen if the // text of the document changes, or the ParseOptions change. So we get the checksums // for both of those, and merge them together to make the final checksum. // // We also want the checksum to change any time our serialization format changes. If // the format has changed, all previous versions should be invalidated. var project = document.Project; var parseOptionsChecksum = project.State.GetParseOptionsChecksum(); var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = documentChecksumState.Text; return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum); } private async Task<bool> SaveAsync( Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>(); try { var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(writer); } stream.Position = 0; return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } private static async Task<bool> PrecalculatedAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>(); // check whether we already have info for this document try { var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // Check if we've already stored a checksum and it matches the checksum we // expect. If so, we're already precalculated and don't have to recompute // this index. Otherwise if we don't have a checksum, or the checksums don't // match, go ahead and recompute it. return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { _literalInfo.WriteTo(writer); _identifierInfo.WriteTo(writer); _contextInfo.WriteTo(writer); _declarationInfo.WriteTo(writer); _extensionMethodInfo.WriteTo(writer); } private static SyntaxTreeIndex? ReadFrom( StringTable stringTable, ObjectReader reader, Checksum? checksum) { var literalInfo = LiteralInfo.TryReadFrom(reader); var identifierInfo = IdentifierInfo.TryReadFrom(reader); var contextInfo = ContextInfo.TryReadFrom(reader); var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader); var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader); if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null) { return null; } return new SyntaxTreeIndex( checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed partial class SyntaxTreeIndex : IObjectWritable { private const string PersistenceName = "<SyntaxTreeIndex>"; private static readonly Checksum SerializationFormatChecksum = Checksum.Create("23"); public readonly Checksum? Checksum; private static Task<SyntaxTreeIndex?> LoadAsync(Document document, Checksum checksum, CancellationToken cancellationToken) => LoadAsync(document.Project.Solution.Workspace, DocumentKey.ToDocumentKey(document), checksum, GetStringTable(document.Project), cancellationToken); public static async Task<SyntaxTreeIndex?> LoadAsync( Workspace workspace, DocumentKey documentKey, Checksum? checksum, StringTable stringTable, CancellationToken cancellationToken) { try { var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetRequiredService<IPersistentStorageService>(); var storage = await persistentStorageService.GetStorageAsync( workspace, documentKey.Project.Solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // attempt to load from persisted state using var stream = await storage.ReadStreamAsync(documentKey, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); using var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken); if (reader != null) return ReadFrom(stringTable, reader, checksum); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return null; } public static async Task<Checksum> GetChecksumAsync( Document document, CancellationToken cancellationToken) { // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change // any time the SyntaxTree could have changed. Right now, that can only happen if the // text of the document changes, or the ParseOptions change. So we get the checksums // for both of those, and merge them together to make the final checksum. // // We also want the checksum to change any time our serialization format changes. If // the format has changed, all previous versions should be invalidated. var project = document.Project; var parseOptionsChecksum = project.State.GetParseOptionsChecksum(); var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var textChecksum = documentChecksumState.Text; return Checksum.Create(textChecksum, parseOptionsChecksum, SerializationFormatChecksum); } private async Task<bool> SaveAsync( Document document, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>(); try { var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken)) { WriteTo(writer); } stream.Position = 0; return await storage.WriteStreamAsync(document, PersistenceName, stream, this.Checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } private static async Task<bool> PrecalculatedAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { var solution = document.Project.Solution; var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetRequiredService<IPersistentStorageService>(); // check whether we already have info for this document try { var storage = await persistentStorageService.GetStorageAsync(solution, checkBranchId: false, cancellationToken).ConfigureAwait(false); await using var _ = storage.ConfigureAwait(false); // Check if we've already stored a checksum and it matches the checksum we // expect. If so, we're already precalculated and don't have to recompute // this index. Otherwise if we don't have a checksum, or the checksums don't // match, go ahead and recompute it. return await storage.ChecksumMatchesAsync(document, PersistenceName, checksum, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (IOUtilities.IsNormalIOException(e)) { // Storage APIs can throw arbitrary exceptions. } return false; } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { _literalInfo.WriteTo(writer); _identifierInfo.WriteTo(writer); _contextInfo.WriteTo(writer); _declarationInfo.WriteTo(writer); _extensionMethodInfo.WriteTo(writer); } private static SyntaxTreeIndex? ReadFrom( StringTable stringTable, ObjectReader reader, Checksum? checksum) { var literalInfo = LiteralInfo.TryReadFrom(reader); var identifierInfo = IdentifierInfo.TryReadFrom(reader); var contextInfo = ContextInfo.TryReadFrom(reader); var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader); var extensionMethodInfo = ExtensionMethodInfo.TryReadFrom(reader); if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null || extensionMethodInfo == null) { return null; } return new SyntaxTreeIndex( checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value, extensionMethodInfo.Value); } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/LanguageServices/DeclaredSymbolFactoryService/AbstractDeclaredSymbolInfoFactoryService.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.Text; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractDeclaredSymbolInfoFactoryService< TCompilationUnitSyntax, TUsingDirectiveSyntax, TNamespaceDeclarationSyntax, TTypeDeclarationSyntax, TEnumDeclarationSyntax, TMemberDeclarationSyntax, TNameSyntax, TQualifiedNameSyntax, TIdentifierNameSyntax> : IDeclaredSymbolInfoFactoryService where TCompilationUnitSyntax : SyntaxNode where TUsingDirectiveSyntax : SyntaxNode where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax where TTypeDeclarationSyntax : TMemberDeclarationSyntax where TEnumDeclarationSyntax : TMemberDeclarationSyntax where TMemberDeclarationSyntax : SyntaxNode where TNameSyntax : SyntaxNode where TQualifiedNameSyntax : TNameSyntax where TIdentifierNameSyntax : TNameSyntax { private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool = SharedPools.Default<List<Dictionary<string, string>>>(); // Note: these names are stored case insensitively. That way the alias mapping works // properly for VB. It will mean that our inheritance maps may store more links in them // for C#. However, that's ok. It will be rare in practice, and all it means is that // we'll end up examining slightly more types (likely 0) when doing operations like // Find all references. private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool = SharedPools.StringIgnoreCaseDictionary<string>(); protected AbstractDeclaredSymbolInfoFactoryService() { } protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node); protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node); protected abstract TNameSyntax GetName(TNamespaceDeclarationSyntax node); protected abstract TNameSyntax GetLeft(TQualifiedNameSyntax node); protected abstract TNameSyntax GetRight(TQualifiedNameSyntax node); protected abstract SyntaxToken GetIdentifier(TIdentifierNameSyntax node); protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration); protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace); protected abstract void AddDeclaredSymbolInfosWorker( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken); /// <summary> /// Get the name of the target type of specified extension method declaration. /// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()` /// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`. /// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>). /// </summary> protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node); protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases); protected abstract string GetRootNamespace(CompilationOptions compilationOptions); protected static List<Dictionary<string, string>> AllocateAliasMapList() => s_aliasMapListPool.Allocate(); // We do not differentiate arrays of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. protected static string CreateReceiverTypeString(string typeName, bool isArray) { if (string.IsNullOrEmpty(typeName)) { return isArray ? FindSymbols.Extensions.ComplexArrayReceiverTypeName : FindSymbols.Extensions.ComplexReceiverTypeName; } else { return isArray ? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix : typeName; } } protected static string CreateValueTupleTypeString(int elementCount) { const string ValueTupleName = "ValueTuple"; if (elementCount == 0) { return ValueTupleName; } // A ValueTuple can have up to 8 type parameters. return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount); } protected static void FreeAliasMapList(List<Dictionary<string, string>> list) { if (list != null) { foreach (var aliasMap in list) { FreeAliasMap(aliasMap); } s_aliasMapListPool.ClearAndFree(list); } } protected static void FreeAliasMap(Dictionary<string, string> aliasMap) { if (aliasMap != null) { s_aliasMapPool.ClearAndFree(aliasMap); } } protected static Dictionary<string, string> AllocateAliasMap() => s_aliasMapPool.Allocate(); protected static void AppendTokens(SyntaxNode node, StringBuilder builder) { foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) { builder.Append(child.AsToken().Text); } else { AppendTokens(child.AsNode(), builder); } } } protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder) { for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = stringTable.Add(builder[i]); } } public void AddDeclaredSymbolInfos( Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken) { var project = document.Project; var stringTable = SyntaxTreeIndex.GetStringTable(project); var rootNamespace = this.GetRootNamespace(project.CompilationOptions); using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases); foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren((TCompilationUnitSyntax)root)) AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken); } private void AddDeclaredSymbolInfos( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, string rootNamespace, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration) { AddNamespaceDeclaredSymbolInfos(GetName(namespaceDeclaration), fullyQualifiedContainerName); var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var usingAlias in GetUsingAliases(namespaceDeclaration)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren(namespaceDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(baseTypeDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(enumDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } AddDeclaredSymbolInfosWorker( container, memberDeclaration, stringTable, declaredSymbolInfos, aliases, extensionMethodInfo, containerDisplayName, fullyQualifiedContainerName, cancellationToken); return; // Returns the new fully-qualified-container-name built from fullyQualifiedContainerName // with all the pieces of 'name' added to the end of it. string AddNamespaceDeclaredSymbolInfos(TNameSyntax name, string fullyQualifiedContainerName) { if (name is TQualifiedNameSyntax qualifiedName) { // Recurse down the left side of the qualified name. Build up the new fully qualified // parent name for when going down the right side. var parentQualifiedContainerName = AddNamespaceDeclaredSymbolInfos(GetLeft(qualifiedName), fullyQualifiedContainerName); return AddNamespaceDeclaredSymbolInfos(GetRight(qualifiedName), parentQualifiedContainerName); } else if (name is TIdentifierNameSyntax nameSyntax) { var namespaceName = GetIdentifier(nameSyntax).ValueText; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, namespaceName, nameSuffix: null, containerDisplayName: null, fullyQualifiedContainerName, isPartial: true, DeclaredSymbolInfoKind.Namespace, Accessibility.Public, nameSyntax.Span, inheritanceNames: ImmutableArray<string>.Empty)); return string.IsNullOrEmpty(fullyQualifiedContainerName) ? namespaceName : fullyQualifiedContainerName + "." + namespaceName; } else { return fullyQualifiedContainerName; } } } protected void AddExtensionMethodInfo( TMemberDeclarationSyntax node, Dictionary<string, string> aliases, int declaredSymbolInfoIndex, Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder) { var receiverTypeName = this.GetReceiverTypeName(node); // Target type is an alias if (aliases.TryGetValue(receiverTypeName, out var originalName)) { // it is an alias of multiple with identical name, // simply treat it as a complex method. if (originalName == null) { receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName; } else { // replace the alias with its original name. receiverTypeName = originalName; } } if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder)) { arrayBuilder = ArrayBuilder<int>.GetInstance(); extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder; } arrayBuilder.Add(declaredSymbolInfoIndex); } private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases) { foreach (var (aliasName, name) in aliases) { // In C#, it's valid to declare two alias with identical name, // as long as they are in different containers. // // e.g. // using X = System.String; // namespace N // { // using X = System.Int32; // } // // If we detect this, we will simply treat extension methods whose // target type is this alias as complex method. if (allAliases.ContainsKey(aliasName)) { allAliases[aliasName] = null; } else { allAliases[aliasName] = name; } } } } }
// 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.Text; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract class AbstractDeclaredSymbolInfoFactoryService< TCompilationUnitSyntax, TUsingDirectiveSyntax, TNamespaceDeclarationSyntax, TTypeDeclarationSyntax, TEnumDeclarationSyntax, TMemberDeclarationSyntax, TNameSyntax, TQualifiedNameSyntax, TIdentifierNameSyntax> : IDeclaredSymbolInfoFactoryService where TCompilationUnitSyntax : SyntaxNode where TUsingDirectiveSyntax : SyntaxNode where TNamespaceDeclarationSyntax : TMemberDeclarationSyntax where TTypeDeclarationSyntax : TMemberDeclarationSyntax where TEnumDeclarationSyntax : TMemberDeclarationSyntax where TMemberDeclarationSyntax : SyntaxNode where TNameSyntax : SyntaxNode where TQualifiedNameSyntax : TNameSyntax where TIdentifierNameSyntax : TNameSyntax { private static readonly ObjectPool<List<Dictionary<string, string>>> s_aliasMapListPool = SharedPools.Default<List<Dictionary<string, string>>>(); // Note: these names are stored case insensitively. That way the alias mapping works // properly for VB. It will mean that our inheritance maps may store more links in them // for C#. However, that's ok. It will be rare in practice, and all it means is that // we'll end up examining slightly more types (likely 0) when doing operations like // Find all references. private static readonly ObjectPool<Dictionary<string, string>> s_aliasMapPool = SharedPools.StringIgnoreCaseDictionary<string>(); protected AbstractDeclaredSymbolInfoFactoryService() { } protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TCompilationUnitSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TNamespaceDeclarationSyntax node); protected abstract SyntaxList<TMemberDeclarationSyntax> GetChildren(TTypeDeclarationSyntax node); protected abstract IEnumerable<TMemberDeclarationSyntax> GetChildren(TEnumDeclarationSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TCompilationUnitSyntax node); protected abstract SyntaxList<TUsingDirectiveSyntax> GetUsingAliases(TNamespaceDeclarationSyntax node); protected abstract TNameSyntax GetName(TNamespaceDeclarationSyntax node); protected abstract TNameSyntax GetLeft(TQualifiedNameSyntax node); protected abstract TNameSyntax GetRight(TQualifiedNameSyntax node); protected abstract SyntaxToken GetIdentifier(TIdentifierNameSyntax node); protected abstract string GetContainerDisplayName(TMemberDeclarationSyntax namespaceDeclaration); protected abstract string GetFullyQualifiedContainerName(TMemberDeclarationSyntax memberDeclaration, string rootNamespace); protected abstract void AddDeclaredSymbolInfosWorker( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken); /// <summary> /// Get the name of the target type of specified extension method declaration. /// The node provided must be an extension method declaration, i.e. calling `TryGetDeclaredSymbolInfo()` /// on `node` should return a `DeclaredSymbolInfo` of kind `ExtensionMethod`. /// If the return value is null, then it means this is a "complex" method (as described at <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>). /// </summary> protected abstract string GetReceiverTypeName(TMemberDeclarationSyntax node); protected abstract bool TryGetAliasesFromUsingDirective(TUsingDirectiveSyntax node, out ImmutableArray<(string aliasName, string name)> aliases); protected abstract string GetRootNamespace(CompilationOptions compilationOptions); protected static List<Dictionary<string, string>> AllocateAliasMapList() => s_aliasMapListPool.Allocate(); // We do not differentiate arrays of different kinds for simplicity. // e.g. int[], int[][], int[,], etc. are all represented as int[] in the index. protected static string CreateReceiverTypeString(string typeName, bool isArray) { if (string.IsNullOrEmpty(typeName)) { return isArray ? FindSymbols.Extensions.ComplexArrayReceiverTypeName : FindSymbols.Extensions.ComplexReceiverTypeName; } else { return isArray ? typeName + FindSymbols.Extensions.ArrayReceiverTypeNameSuffix : typeName; } } protected static string CreateValueTupleTypeString(int elementCount) { const string ValueTupleName = "ValueTuple"; if (elementCount == 0) { return ValueTupleName; } // A ValueTuple can have up to 8 type parameters. return ValueTupleName + ArityUtilities.GetMetadataAritySuffix(elementCount > 8 ? 8 : elementCount); } protected static void FreeAliasMapList(List<Dictionary<string, string>> list) { if (list != null) { foreach (var aliasMap in list) { FreeAliasMap(aliasMap); } s_aliasMapListPool.ClearAndFree(list); } } protected static void FreeAliasMap(Dictionary<string, string> aliasMap) { if (aliasMap != null) { s_aliasMapPool.ClearAndFree(aliasMap); } } protected static Dictionary<string, string> AllocateAliasMap() => s_aliasMapPool.Allocate(); protected static void AppendTokens(SyntaxNode node, StringBuilder builder) { foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) { builder.Append(child.AsToken().Text); } else { AppendTokens(child.AsNode(), builder); } } } protected static void Intern(StringTable stringTable, ArrayBuilder<string> builder) { for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = stringTable.Add(builder[i]); } } public void AddDeclaredSymbolInfos( Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken) { var project = document.Project; var stringTable = SyntaxTreeIndex.GetStringTable(project); var rootNamespace = this.GetRootNamespace(project.CompilationOptions); using var _1 = PooledDictionary<string, string>.GetInstance(out var aliases); foreach (var usingAlias in GetUsingAliases((TCompilationUnitSyntax)root)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren((TCompilationUnitSyntax)root)) AddDeclaredSymbolInfos(root, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, "", "", cancellationToken); } private void AddDeclaredSymbolInfos( SyntaxNode container, TMemberDeclarationSyntax memberDeclaration, StringTable stringTable, string rootNamespace, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, string> aliases, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, string containerDisplayName, string fullyQualifiedContainerName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (memberDeclaration is TNamespaceDeclarationSyntax namespaceDeclaration) { AddNamespaceDeclaredSymbolInfos(GetName(namespaceDeclaration), fullyQualifiedContainerName); var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var usingAlias in GetUsingAliases(namespaceDeclaration)) { if (this.TryGetAliasesFromUsingDirective(usingAlias, out var current)) AddAliases(aliases, current); } foreach (var child in GetChildren(namespaceDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TTypeDeclarationSyntax baseTypeDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(baseTypeDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } else if (memberDeclaration is TEnumDeclarationSyntax enumDeclaration) { var innerContainerDisplayName = GetContainerDisplayName(memberDeclaration); var innerFullyQualifiedContainerName = GetFullyQualifiedContainerName(memberDeclaration, rootNamespace); foreach (var child in GetChildren(enumDeclaration)) { AddDeclaredSymbolInfos( memberDeclaration, child, stringTable, rootNamespace, declaredSymbolInfos, aliases, extensionMethodInfo, innerContainerDisplayName, innerFullyQualifiedContainerName, cancellationToken); } } AddDeclaredSymbolInfosWorker( container, memberDeclaration, stringTable, declaredSymbolInfos, aliases, extensionMethodInfo, containerDisplayName, fullyQualifiedContainerName, cancellationToken); return; // Returns the new fully-qualified-container-name built from fullyQualifiedContainerName // with all the pieces of 'name' added to the end of it. string AddNamespaceDeclaredSymbolInfos(TNameSyntax name, string fullyQualifiedContainerName) { if (name is TQualifiedNameSyntax qualifiedName) { // Recurse down the left side of the qualified name. Build up the new fully qualified // parent name for when going down the right side. var parentQualifiedContainerName = AddNamespaceDeclaredSymbolInfos(GetLeft(qualifiedName), fullyQualifiedContainerName); return AddNamespaceDeclaredSymbolInfos(GetRight(qualifiedName), parentQualifiedContainerName); } else if (name is TIdentifierNameSyntax nameSyntax) { var namespaceName = GetIdentifier(nameSyntax).ValueText; declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, namespaceName, nameSuffix: null, containerDisplayName: null, fullyQualifiedContainerName, isPartial: true, DeclaredSymbolInfoKind.Namespace, Accessibility.Public, nameSyntax.Span, inheritanceNames: ImmutableArray<string>.Empty)); return string.IsNullOrEmpty(fullyQualifiedContainerName) ? namespaceName : fullyQualifiedContainerName + "." + namespaceName; } else { return fullyQualifiedContainerName; } } } protected void AddExtensionMethodInfo( TMemberDeclarationSyntax node, Dictionary<string, string> aliases, int declaredSymbolInfoIndex, Dictionary<string, ArrayBuilder<int>> extensionMethodsInfoBuilder) { var receiverTypeName = this.GetReceiverTypeName(node); // Target type is an alias if (aliases.TryGetValue(receiverTypeName, out var originalName)) { // it is an alias of multiple with identical name, // simply treat it as a complex method. if (originalName == null) { receiverTypeName = FindSymbols.Extensions.ComplexReceiverTypeName; } else { // replace the alias with its original name. receiverTypeName = originalName; } } if (!extensionMethodsInfoBuilder.TryGetValue(receiverTypeName, out var arrayBuilder)) { arrayBuilder = ArrayBuilder<int>.GetInstance(); extensionMethodsInfoBuilder[receiverTypeName] = arrayBuilder; } arrayBuilder.Add(declaredSymbolInfoIndex); } private static void AddAliases(Dictionary<string, string> allAliases, ImmutableArray<(string aliasName, string name)> aliases) { foreach (var (aliasName, name) in aliases) { // In C#, it's valid to declare two alias with identical name, // as long as they are in different containers. // // e.g. // using X = System.String; // namespace N // { // using X = System.Int32; // } // // If we detect this, we will simply treat extension methods whose // target type is this alias as complex method. if (allAliases.ContainsKey(aliasName)) { allAliases[aliasName] = null; } else { allAliases[aliasName] = name; } } } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Workspace/Solution/Project.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a project that is part of a <see cref="Solution"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Project { private readonly Solution _solution; private readonly ProjectState _projectState; private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty; private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty; private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty; private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty; internal Project(Solution solution, ProjectState projectState) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(projectState); _solution = solution; _projectState = projectState; } internal ProjectState State => _projectState; /// <summary> /// The solution this project is part of. /// </summary> public Solution Solution => _solution; /// <summary> /// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only /// one project may have this ID in any given solution. /// </summary> public ProjectId Id => _projectState.Id; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => _projectState.FilePath; /// <summary> /// The path to the output file, or null if it is not known. /// </summary> public string? OutputFilePath => _projectState.OutputFilePath; /// <summary> /// The path to the reference assembly output file, or null if it is not known. /// </summary> public string? OutputRefFilePath => _projectState.OutputRefFilePath; /// <summary> /// Compilation output file paths. /// </summary> public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various feature can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> public string? DefaultNamespace => _projectState.DefaultNamespace; /// <summary> /// <see langword="true"/> if this <see cref="Project"/> supports providing data through the /// <see cref="GetCompilationAsync(CancellationToken)"/> method. /// /// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead. /// </summary> public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; /// <summary> /// The language services from the host environment associated with this project's language. /// </summary> public HostLanguageServices LanguageServices => _projectState.LanguageServices; /// <summary> /// The language associated with the project. /// </summary> public string Language => _projectState.Language; /// <summary> /// The name of the assembly this project represents. /// </summary> public string AssemblyName => _projectState.AssemblyName; /// <summary> /// The name of the project. This may be different than the assembly name. /// </summary> public string Name => _projectState.Name; /// <summary> /// The list of all other metadata sources (assemblies) that this project references. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences; /// <summary> /// The list of all other projects within the same solution that this project references. /// </summary> public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId)); /// <summary> /// The list of all other projects that this project references, including projects that /// are not part of the solution. /// </summary> public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences; /// <summary> /// The list of all the diagnostic analyzer references for this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences; /// <summary> /// The options used by analyzers for this project. /// </summary> public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions; /// <summary> /// The options used when building the compilation for this project. /// </summary> public CompilationOptions? CompilationOptions => _projectState.CompilationOptions; /// <summary> /// The options used when parsing documents for this project. /// </summary> public ParseOptions? ParseOptions => _projectState.ParseOptions; /// <summary> /// Returns true if this is a submission project. /// </summary> public bool IsSubmission => _projectState.IsSubmission; /// <summary> /// True if the project has any documents. /// </summary> public bool HasDocuments => !_projectState.DocumentStates.IsEmpty; /// <summary> /// All the document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids; /// <summary> /// All the regular documents associated with this project. Documents produced from source generators are returned by /// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>. /// </summary> public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!; /// <summary> /// All the additional documents associated with this project. /// </summary> public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!; /// <summary> /// All the <see cref="AnalyzerConfigDocument"/>s associated with this project. /// </summary> public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!; /// <summary> /// True if the project contains a document with the specified ID. /// </summary> public bool ContainsDocument(DocumentId documentId) => _projectState.DocumentStates.Contains(documentId); /// <summary> /// True if the project contains an additional document with the specified ID. /// </summary> public bool ContainsAdditionalDocument(DocumentId documentId) => _projectState.AdditionalDocumentStates.Contains(documentId); /// <summary> /// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID. /// </summary> public bool ContainsAnalyzerConfigDocument(DocumentId documentId) => _projectState.AnalyzerConfigDocumentStates.Contains(documentId); /// <summary> /// Get the documentId in this project with the specified syntax tree. /// </summary> public DocumentId? GetDocumentId(SyntaxTree? syntaxTree) => _solution.GetDocumentId(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified syntax tree. /// </summary> public Document? GetDocument(SyntaxTree? syntaxTree) => _solution.GetDocument(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified document Id. /// </summary> public Document? GetDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this); /// <summary> /// Get the additional document in this project with the specified document Id. /// </summary> public TextDocument? GetAdditionalDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this); /// <summary> /// Get the analyzer config document in this project with the specified document Id. /// </summary> public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this); /// <summary> /// Gets a document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var document = GetDocument(documentId); if (document != null || !includeSourceGenerated) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId); if (document != null) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all source generated documents in this project. /// </summary> public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); // return an iterator to avoid eagerly allocating all the document instances return generatedDocumentStates.States.Values.Select(state => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!; } internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false)); } public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { // Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument)) { return sourceGeneratedDocument; } // We'll have to run generators if we haven't already and now try to find it. var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false); var generatedDocumentState = generatedDocumentStates.GetState(documentId); if (generatedDocumentState != null) { return GetOrCreateSourceGeneratedDocument(generatedDocumentState); } return null; } internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state) => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!; /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) { // Easy case: do we already have the SourceGeneratedDocument created? if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document)) { return document; } // Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go // try to fetch the state. var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (documentState == null) { return null; } return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this)); } internal Task<bool> ContainsSymbolsWithNameAsync( string name, CancellationToken cancellationToken) { return ContainsSymbolsAsync( (index, cancellationToken) => index.ProbablyContainsIdentifier(name) || index.ProbablyContainsEscapedIdentifier(name), cancellationToken); } internal Task<bool> ContainsSymbolsWithNameAsync( Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { return ContainsSymbolsAsync( (index, cancellationToken) => { foreach (var info in index.DeclaredSymbolInfos) { if (FilterMatches(info, filter) && predicate(info.Name)) return true; } return false; }, cancellationToken); static bool FilterMatches(DeclaredSymbolInfo info, SymbolFilter filter) { switch (info.Kind) { case DeclaredSymbolInfoKind.Namespace: return (filter & SymbolFilter.Namespace) != 0; case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Delegate: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.RecordStruct: case DeclaredSymbolInfoKind.Struct: return (filter & SymbolFilter.Type) != 0; case DeclaredSymbolInfoKind.Constant: case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.EnumMember: case DeclaredSymbolInfoKind.Event: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Field: case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Method: case DeclaredSymbolInfoKind.Property: return (filter & SymbolFilter.Member) != 0; default: throw ExceptionUtilities.UnexpectedValue(info.Kind); } } } private async Task<bool> ContainsSymbolsAsync( Func<SyntaxTreeIndex, CancellationToken, bool> predicate, CancellationToken cancellationToken) { if (!this.SupportsCompilation) return false; var tasks = this.Documents.Select(async d => { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(d, cancellationToken).ConfigureAwait(false); return predicate(index, cancellationToken); }); var results = await Task.WhenAll(tasks).ConfigureAwait(false); return results.Any(b => b); } private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction = (documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null; private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction = (documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null; private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction = (documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null; private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction = (documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state); /// <summary> /// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all /// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/> /// or create a new one otherwise. /// </summary> public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation) => _solution.State.TryGetCompilation(this.Id, out compilation); /// <summary> /// Get the <see cref="Compilation"/> for this project asynchronously. /// </summary> /// <returns> /// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see /// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default) => _solution.State.GetCompilationAsync(_projectState, cancellationToken); /// <summary> /// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects. /// </summary> // TODO: make this public internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default) => _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken); /// <summary> /// Gets an object that lists the added, changed and removed documents between this project and the specified project. /// </summary> public ProjectChanges GetChanges(Project oldProject) { if (oldProject == null) { throw new ArgumentNullException(nameof(oldProject)); } return new ProjectChanges(this, oldProject); } /// <summary> /// The project version. This equates to the version of the project file. /// </summary> public VersionStamp Version => _projectState.Version; /// <summary> /// The version of the most recently modified document. /// </summary> public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetLatestDocumentVersionAsync(cancellationToken); /// <summary> /// The most recent version of the project, its documents and all dependent projects and documents. /// </summary> public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project including the semantics of referenced projects. /// This version changes whenever the consumable declarations of this project and/or projects it depends on change. /// </summary> public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project not including the semantics of referenced projects. /// This version changes only when the consumable declarations of this project change. /// </summary> public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetSemanticVersionAsync(cancellationToken); /// <summary> /// Creates a new instance of this project updated to have the new assembly name. /// </summary> public Project WithAssemblyName(string assemblyName) => this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the new default namespace. /// </summary> public Project WithDefaultNamespace(string defaultNamespace) => this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified compilation options. /// </summary> public Project WithCompilationOptions(CompilationOptions options) => this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified parse options. /// </summary> public Project WithParseOptions(ParseOptions options) => this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project reference /// in addition to already existing ones. /// </summary> public Project AddProjectReference(ProjectReference projectReference) => this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project references /// in addition to already existing ones. /// </summary> public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified project reference. /// </summary> public Project RemoveProjectReference(ProjectReference projectReference) => this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing project references /// with the specified ones. /// </summary> public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata reference /// in addition to already existing ones. /// </summary> public Project AddMetadataReference(MetadataReference metadataReference) => this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata references /// in addition to already existing ones. /// </summary> public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) => this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing metadata reference /// with the specified ones. /// </summary> public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer reference /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer references /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) => this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer reference. /// </summary> public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing analyzer references /// with the specified ones. /// </summary> public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs) => this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!; /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); // use preserve identity for forked solution directly from syntax node. // this lets us not serialize temporary tree unnecessarily return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id, debugName: name); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new analyzer config document in a new instance of this project. /// </summary> public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified document. /// </summary> public Project RemoveDocument(DocumentId documentId) { // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified documents. /// </summary> public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional document. /// </summary> public Project RemoveAdditionalDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional documents. /// </summary> public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer config document. /// </summary> public Project RemoveAnalyzerConfigDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s. /// </summary> public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id); } private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds) { foreach (var documentId in documentIds) { // Dealing with nulls is handled by the caller of this if (documentId?.ProjectId != this.Id) { throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId)); } } } internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() => _projectState.GetAnalyzerConfigOptions(); private string GetDebuggerDisplay() => this.Name; internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache) => Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache); } }
// 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a project that is part of a <see cref="Solution"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Project { private readonly Solution _solution; private readonly ProjectState _projectState; private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty; private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty; private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty; private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty; internal Project(Solution solution, ProjectState projectState) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(projectState); _solution = solution; _projectState = projectState; } internal ProjectState State => _projectState; /// <summary> /// The solution this project is part of. /// </summary> public Solution Solution => _solution; /// <summary> /// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only /// one project may have this ID in any given solution. /// </summary> public ProjectId Id => _projectState.Id; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => _projectState.FilePath; /// <summary> /// The path to the output file, or null if it is not known. /// </summary> public string? OutputFilePath => _projectState.OutputFilePath; /// <summary> /// The path to the reference assembly output file, or null if it is not known. /// </summary> public string? OutputRefFilePath => _projectState.OutputRefFilePath; /// <summary> /// Compilation output file paths. /// </summary> public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various feature can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> public string? DefaultNamespace => _projectState.DefaultNamespace; /// <summary> /// <see langword="true"/> if this <see cref="Project"/> supports providing data through the /// <see cref="GetCompilationAsync(CancellationToken)"/> method. /// /// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead. /// </summary> public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; /// <summary> /// The language services from the host environment associated with this project's language. /// </summary> public HostLanguageServices LanguageServices => _projectState.LanguageServices; /// <summary> /// The language associated with the project. /// </summary> public string Language => _projectState.Language; /// <summary> /// The name of the assembly this project represents. /// </summary> public string AssemblyName => _projectState.AssemblyName; /// <summary> /// The name of the project. This may be different than the assembly name. /// </summary> public string Name => _projectState.Name; /// <summary> /// The list of all other metadata sources (assemblies) that this project references. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences; /// <summary> /// The list of all other projects within the same solution that this project references. /// </summary> public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId)); /// <summary> /// The list of all other projects that this project references, including projects that /// are not part of the solution. /// </summary> public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences; /// <summary> /// The list of all the diagnostic analyzer references for this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences; /// <summary> /// The options used by analyzers for this project. /// </summary> public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions; /// <summary> /// The options used when building the compilation for this project. /// </summary> public CompilationOptions? CompilationOptions => _projectState.CompilationOptions; /// <summary> /// The options used when parsing documents for this project. /// </summary> public ParseOptions? ParseOptions => _projectState.ParseOptions; /// <summary> /// Returns true if this is a submission project. /// </summary> public bool IsSubmission => _projectState.IsSubmission; /// <summary> /// True if the project has any documents. /// </summary> public bool HasDocuments => !_projectState.DocumentStates.IsEmpty; /// <summary> /// All the document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids; /// <summary> /// All the regular documents associated with this project. Documents produced from source generators are returned by /// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>. /// </summary> public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!; /// <summary> /// All the additional documents associated with this project. /// </summary> public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!; /// <summary> /// All the <see cref="AnalyzerConfigDocument"/>s associated with this project. /// </summary> public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!; /// <summary> /// True if the project contains a document with the specified ID. /// </summary> public bool ContainsDocument(DocumentId documentId) => _projectState.DocumentStates.Contains(documentId); /// <summary> /// True if the project contains an additional document with the specified ID. /// </summary> public bool ContainsAdditionalDocument(DocumentId documentId) => _projectState.AdditionalDocumentStates.Contains(documentId); /// <summary> /// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID. /// </summary> public bool ContainsAnalyzerConfigDocument(DocumentId documentId) => _projectState.AnalyzerConfigDocumentStates.Contains(documentId); /// <summary> /// Get the documentId in this project with the specified syntax tree. /// </summary> public DocumentId? GetDocumentId(SyntaxTree? syntaxTree) => _solution.GetDocumentId(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified syntax tree. /// </summary> public Document? GetDocument(SyntaxTree? syntaxTree) => _solution.GetDocument(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified document Id. /// </summary> public Document? GetDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this); /// <summary> /// Get the additional document in this project with the specified document Id. /// </summary> public TextDocument? GetAdditionalDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this); /// <summary> /// Get the analyzer config document in this project with the specified document Id. /// </summary> public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this); /// <summary> /// Gets a document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var document = GetDocument(documentId); if (document != null || !includeSourceGenerated) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId); if (document != null) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all source generated documents in this project. /// </summary> public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); // return an iterator to avoid eagerly allocating all the document instances return generatedDocumentStates.States.Values.Select(state => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!; } internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false)); } public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { // Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument)) { return sourceGeneratedDocument; } // We'll have to run generators if we haven't already and now try to find it. var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false); var generatedDocumentState = generatedDocumentStates.GetState(documentId); if (generatedDocumentState != null) { return GetOrCreateSourceGeneratedDocument(generatedDocumentState); } return null; } internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state) => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!; /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) { // Easy case: do we already have the SourceGeneratedDocument created? if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document)) { return document; } // Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go // try to fetch the state. var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (documentState == null) { return null; } return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this)); } internal Task<bool> ContainsSymbolsWithNameAsync( string name, CancellationToken cancellationToken) { return ContainsSymbolsAsync( (index, cancellationToken) => index.ProbablyContainsIdentifier(name) || index.ProbablyContainsEscapedIdentifier(name), cancellationToken); } internal Task<bool> ContainsSymbolsWithNameAsync( Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { return ContainsSymbolsAsync( (index, cancellationToken) => { foreach (var info in index.DeclaredSymbolInfos) { if (FilterMatches(info, filter) && predicate(info.Name)) return true; } return false; }, cancellationToken); static bool FilterMatches(DeclaredSymbolInfo info, SymbolFilter filter) { switch (info.Kind) { case DeclaredSymbolInfoKind.Namespace: return (filter & SymbolFilter.Namespace) != 0; case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Delegate: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.RecordStruct: case DeclaredSymbolInfoKind.Struct: return (filter & SymbolFilter.Type) != 0; case DeclaredSymbolInfoKind.Constant: case DeclaredSymbolInfoKind.Constructor: case DeclaredSymbolInfoKind.EnumMember: case DeclaredSymbolInfoKind.Event: case DeclaredSymbolInfoKind.ExtensionMethod: case DeclaredSymbolInfoKind.Field: case DeclaredSymbolInfoKind.Indexer: case DeclaredSymbolInfoKind.Method: case DeclaredSymbolInfoKind.Property: return (filter & SymbolFilter.Member) != 0; default: throw ExceptionUtilities.UnexpectedValue(info.Kind); } } } private async Task<bool> ContainsSymbolsAsync( Func<SyntaxTreeIndex, CancellationToken, bool> predicate, CancellationToken cancellationToken) { if (!this.SupportsCompilation) return false; var tasks = this.Documents.Select(async d => { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(d, cancellationToken).ConfigureAwait(false); return predicate(index, cancellationToken); }); var results = await Task.WhenAll(tasks).ConfigureAwait(false); return results.Any(b => b); } private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction = (documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null; private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction = (documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null; private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction = (documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null; private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction = (documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state); /// <summary> /// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all /// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/> /// or create a new one otherwise. /// </summary> public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation) => _solution.State.TryGetCompilation(this.Id, out compilation); /// <summary> /// Get the <see cref="Compilation"/> for this project asynchronously. /// </summary> /// <returns> /// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see /// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default) => _solution.State.GetCompilationAsync(_projectState, cancellationToken); /// <summary> /// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects. /// </summary> // TODO: make this public internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default) => _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken); /// <summary> /// Gets an object that lists the added, changed and removed documents between this project and the specified project. /// </summary> public ProjectChanges GetChanges(Project oldProject) { if (oldProject == null) { throw new ArgumentNullException(nameof(oldProject)); } return new ProjectChanges(this, oldProject); } /// <summary> /// The project version. This equates to the version of the project file. /// </summary> public VersionStamp Version => _projectState.Version; /// <summary> /// The version of the most recently modified document. /// </summary> public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetLatestDocumentVersionAsync(cancellationToken); /// <summary> /// The most recent version of the project, its documents and all dependent projects and documents. /// </summary> public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project including the semantics of referenced projects. /// This version changes whenever the consumable declarations of this project and/or projects it depends on change. /// </summary> public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project not including the semantics of referenced projects. /// This version changes only when the consumable declarations of this project change. /// </summary> public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetSemanticVersionAsync(cancellationToken); /// <summary> /// Creates a new instance of this project updated to have the new assembly name. /// </summary> public Project WithAssemblyName(string assemblyName) => this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the new default namespace. /// </summary> public Project WithDefaultNamespace(string defaultNamespace) => this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified compilation options. /// </summary> public Project WithCompilationOptions(CompilationOptions options) => this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified parse options. /// </summary> public Project WithParseOptions(ParseOptions options) => this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project reference /// in addition to already existing ones. /// </summary> public Project AddProjectReference(ProjectReference projectReference) => this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project references /// in addition to already existing ones. /// </summary> public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified project reference. /// </summary> public Project RemoveProjectReference(ProjectReference projectReference) => this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing project references /// with the specified ones. /// </summary> public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata reference /// in addition to already existing ones. /// </summary> public Project AddMetadataReference(MetadataReference metadataReference) => this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata references /// in addition to already existing ones. /// </summary> public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) => this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing metadata reference /// with the specified ones. /// </summary> public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer reference /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer references /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) => this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer reference. /// </summary> public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing analyzer references /// with the specified ones. /// </summary> public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs) => this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!; /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); // use preserve identity for forked solution directly from syntax node. // this lets us not serialize temporary tree unnecessarily return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id, debugName: name); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new analyzer config document in a new instance of this project. /// </summary> public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified document. /// </summary> public Project RemoveDocument(DocumentId documentId) { // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified documents. /// </summary> public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional document. /// </summary> public Project RemoveAdditionalDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional documents. /// </summary> public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer config document. /// </summary> public Project RemoveAnalyzerConfigDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s. /// </summary> public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id); } private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds) { foreach (var documentId in documentIds) { // Dealing with nulls is handled by the caller of this if (documentId?.ProjectId != this.Id) { throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId)); } } } internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() => _projectState.GetAnalyzerConfigOptions(); private string GetDebuggerDisplay() => this.Name; internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache) => Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache); } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private CompilationTrackerState _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, CompilationTrackerState state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, CompilationTrackerState.Empty) { } private CompilationTrackerState ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(CompilationTrackerState state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = CompilationTrackerState.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } else { // We have no compilation, but we might have information about generated docs. var newState = new NoCompilationState(state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false); return new CompilationTracker(newProject, newState); } } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync( solutionServices, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal, cancellationToken).ConfigureAwait(false); } if (state is AllSyntaxTreesParsedState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private async Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // We've got nothing. Build it from scratch :( return await BuildCompilationInfoFromScratchAsync( solution, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, generatorDriver, cancellationToken).ConfigureAwait(false); } if (state is AllSyntaxTreesParsedState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken).ConfigureAwait(false); } else { // We must have an in progress compilation. Build off of that. return await BuildFinalStateFromInProgressStateAsync( solution, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync( solution.Services, nonAuthoritativeGeneratedDocuments, generatorDriver, generatedDocumentsAreFinal: false, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments, GeneratorDriver? generatorDriver, bool generatedDocumentsAreFinal, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); using var _ = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count, out var trees); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); WriteState(new AllSyntaxTreesParsedState(compilation, generatedDocuments, generatorDriver, generatedDocumentsAreFinal), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(CompilationTrackerState.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( CompilationTrackerState.CreateValueSource(compilationWithGenerators, solution.Services), CompilationTrackerState.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private CompilationTrackerState _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, CompilationTrackerState state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, CompilationTrackerState.Empty) { } private CompilationTrackerState ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(CompilationTrackerState state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = CompilationTrackerState.Create(baseCompilation, state.GeneratorInfo, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } else { // We have no compilation, but we might have information about generated docs. var newState = new NoCompilationState(state.GeneratorInfo.WithDocumentsAreFinal(false)); return new CompilationTracker(newProject, newState); } } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var generatorInfo, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, generatorInfo, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out CompilationTrackerGeneratorInfo generatorInfo, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; generatorInfo = state.GeneratorInfo; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(generatorInfo.Documents.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(generatorInfo.Documents.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync( solutionServices, state.GeneratorInfo, cancellationToken).ConfigureAwait(false); } if (state is AllSyntaxTreesParsedState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratorInfo.Documents); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private async Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratorInfo.Documents); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratorInfo.DocumentsAreFinal ? state.GeneratorInfo.Documents : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratorInfo.Documents; var generatorDriver = state.GeneratorInfo.Driver; if (compilation == null) { // We've got nothing. Build it from scratch :( return await BuildCompilationInfoFromScratchAsync( solution, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, generatorDriver, cancellationToken).ConfigureAwait(false); } if (state is AllSyntaxTreesParsedState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken).ConfigureAwait(false); } else { // We must have an in progress compilation. Build off of that. return await BuildFinalStateFromInProgressStateAsync( solution, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync( solution.Services, new CompilationTrackerGeneratorInfo( nonAuthoritativeGeneratedDocuments, generatorDriver, documentsAreFinal: false), cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CompilationTrackerGeneratorInfo generatorInfo, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); using var _ = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count, out var trees); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); WriteState(new AllSyntaxTreesParsedState(compilation, generatorInfo), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratorInfo.Documents, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorInfo.Driver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(CompilationTrackerState.Create(compilationWithoutGenerators, state.GeneratorInfo.WithDriver(generatorDriver), compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( CompilationTrackerState.CreateValueSource(compilationWithGenerators, solution.Services), CompilationTrackerState.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, new CompilationTrackerGeneratorInfo( generatedDocuments, generatorDriver, documentsAreFinal: true), compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratorInfo.Documents.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #endregion } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
// 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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.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 System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
// 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 System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/VisualBasic/Portable/FindSymbols/VisualBasicDeclaredSymbolInfoFactoryService.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.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols <ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDeclaredSymbolInfoFactoryService Inherits AbstractDeclaredSymbolInfoFactoryService(Of CompilationUnitSyntax, ImportsStatementSyntax, NamespaceBlockSyntax, TypeBlockSyntax, EnumBlockSyntax, StatementSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax) Private Const ExtensionName As String = "Extension" Private Const ExtensionAttributeName As String = "ExtensionAttribute" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String) Dim builder = ArrayBuilder(Of String).GetInstance() Dim aliasMap = GetAliasMap(typeBlock) Try For Each inheritsStatement In typeBlock.Inherits AddInheritanceNames(builder, inheritsStatement.Types, aliasMap) Next For Each implementsStatement In typeBlock.Implements AddInheritanceNames(builder, implementsStatement.Types, aliasMap) Next Intern(stringTable, builder) Return builder.ToImmutableAndFree() Finally FreeAliasMap(aliasMap) End Try End Function Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String) Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot() Dim aliasMap As Dictionary(Of String, String) = Nothing For Each import In compilationUnit.Imports For Each clause In import.ImportsClauses If clause.IsKind(SyntaxKind.SimpleImportsClause) Then Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax) If simpleImport.Alias IsNot Nothing Then Dim mappedName = GetTypeName(simpleImport.Name) If mappedName IsNot Nothing Then aliasMap = If(aliasMap, AllocateAliasMap()) aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName End If End If End If Next Next Return aliasMap End Function Private Shared Sub AddInheritanceNames( builder As ArrayBuilder(Of String), types As SeparatedSyntaxList(Of TypeSyntax), aliasMap As Dictionary(Of String, String)) For Each typeSyntax In types AddInheritanceName(builder, typeSyntax, aliasMap) Next End Sub Private Shared Sub AddInheritanceName( builder As ArrayBuilder(Of String), typeSyntax As TypeSyntax, aliasMap As Dictionary(Of String, String)) Dim name = GetTypeName(typeSyntax) If name IsNot Nothing Then builder.Add(name) Dim mappedName As String = Nothing If aliasMap?.TryGetValue(name, mappedName) = True Then ' Looks Like this could be an alias. Also include the name the alias points to builder.Add(mappedName) End If End If End Sub Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String If TypeOf typeSyntax Is SimpleNameSyntax Then Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax)) ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right) End If Return Nothing End Function Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String Return simpleName.Identifier.ValueText End Function Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters) End Function Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace) End Function Protected Overrides Sub AddDeclaredSymbolInfosWorker( container As SyntaxNode, node As StatementSyntax, stringTable As StringTable, declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo), aliases As Dictionary(Of String, String), extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)), containerDisplayName As String, fullyQualifiedContainerName As String, cancellationToken As CancellationToken) ' If this Is a part of partial type that only contains nested types, then we don't make an info type for it. ' That's because we effectively think of this as just being a virtual container just to hold the nested ' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of ' namespaces. Dim typeDecl = TryCast(node, TypeBlockSyntax) If typeDecl IsNot Nothing AndAlso typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso typeDecl.Members.Any() AndAlso typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then Return End If If node.Kind() = SyntaxKind.PropertyBlock Then node = DirectCast(node, PropertyBlockSyntax).PropertyStatement ElseIf node.Kind() = SyntaxKind.EventBlock Then node = DirectCast(node, EventBlockSyntax).EventStatement ElseIf TypeOf node Is MethodBlockBaseSyntax Then node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement End If Dim kind = node.Kind() Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock Dim typeBlock = CType(node, TypeBlockSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.BlockStatement.Identifier.ValueText, GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword), If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class, If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface, If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module, DeclaredSymbolInfoKind.Struct))), GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers), typeBlock.BlockStatement.Identifier.Span, GetInheritanceNames(stringTable, typeBlock), IsNestedType(typeBlock))) Return Case SyntaxKind.EnumBlock Dim enumDecl = DirectCast(node, EnumBlockSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.EnumStatement.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers), enumDecl.EnumStatement.Identifier.Span, ImmutableArray(Of String).Empty, IsNestedType(enumDecl))) Return Case SyntaxKind.SubNewStatement Dim constructor = DirectCast(node, SubNewStatementSyntax) Dim typeBlock = TryCast(container, TypeBlockSyntax) If typeBlock IsNot Nothing Then declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeBlock.BlockStatement.Identifier.ValueText, GetConstructorSuffix(constructor), containerDisplayName, fullyQualifiedContainerName, constructor.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, constructor, constructor.Modifiers), constructor.NewKeyword.Span, ImmutableArray(Of String).Empty, parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0))) Return End If Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Dim delegateDecl = DirectCast(node, DelegateStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl, delegateDecl.Modifiers), delegateDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.EnumMemberDeclaration Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, isPartial:=False, DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.EventStatement Dim eventDecl = DirectCast(node, EventStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl, eventDecl.Modifiers), eventDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Dim funcDecl = DirectCast(node, MethodStatementSyntax) Dim isExtension = IsExtensionMethod(funcDecl) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, funcDecl.Identifier.ValueText, GetMethodSuffix(funcDecl), containerDisplayName, fullyQualifiedContainerName, funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword), If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method), GetAccessibility(container, funcDecl, funcDecl.Modifiers), funcDecl.Identifier.Span, ImmutableArray(Of String).Empty, parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0), typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0))) If isExtension Then AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo) End If Return Case SyntaxKind.PropertyStatement Dim propertyDecl = DirectCast(node, PropertyStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, propertyDecl.Identifier.ValueText, GetPropertySuffix(propertyDecl), containerDisplayName, fullyQualifiedContainerName, propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, propertyDecl, propertyDecl.Modifiers), propertyDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.FieldDeclaration Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax) For Each variableDeclarator In fieldDecl.Declarators For Each modifiedIdentifier In variableDeclarator.Names declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, modifiedIdentifier.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword), If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword), DeclaredSymbolInfoKind.Constant, DeclaredSymbolInfoKind.Field), GetAccessibility(container, fieldDecl, fieldDecl.Modifiers), modifiedIdentifier.Identifier.Span, ImmutableArray(Of String).Empty)) Next Next End Select End Sub Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax) Return node.Imports End Function Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetName(node As NamespaceBlockSyntax) As NameSyntax Return node.NamespaceStatement.Name End Function Protected Overrides Function GetLeft(node As QualifiedNameSyntax) As NameSyntax Return node.Left End Function Protected Overrides Function GetRight(node As QualifiedNameSyntax) As NameSyntax Return node.Right End Function Protected Overrides Function GetIdentifier(node As IdentifierNameSyntax) As SyntaxToken Return node.Identifier End Function Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean Dim parameterCount = node.ParameterList?.Parameters.Count ' Extension method must have at least one parameter and declared inside a module If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then Return False End If For Each attributeList In node.AttributeLists For Each attribute In attributeList.Attributes ' ExtensionAttribute takes no argument. If attribute.ArgumentList?.Arguments.Count > 0 Then Continue For End If Dim name = attribute.Name.GetRightmostName()?.ToString() If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then Return True End If Next Next Return False End Function Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean Return TypeOf node.Parent Is TypeBlockSyntax End Function Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility Dim sawFriend = False For Each modifier In modifiers Select Case modifier.Kind() Case SyntaxKind.PublicKeyword : Return Accessibility.Public Case SyntaxKind.PrivateKeyword : Return Accessibility.Private Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected Case SyntaxKind.FriendKeyword sawFriend = True Continue For End Select Next If sawFriend Then Return Accessibility.Internal End If ' No accessibility modifiers Select Case container.Kind() Case SyntaxKind.ClassBlock ' In a class, fields and shared-constructors are private by default, ' everything Else Is Public If node.Kind() = SyntaxKind.FieldDeclaration Then Return Accessibility.Private End If If node.Kind() = SyntaxKind.SubNewStatement AndAlso DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then Return Accessibility.Private End If Return Accessibility.Public Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock ' Everything in a struct/interface/module is public Return Accessibility.Public End Select ' Otherwise, it's internal Return Accessibility.Internal End Function Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList) End Function Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String Return ".New" & GetSuffix(method.ParameterList) End Function Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String If [property].ParameterList Is Nothing Then Return Nothing End If Return GetSuffix([property].ParameterList) End Function Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String If typeParameterList Is Nothing Then Return Nothing End If Dim pooledBuilder = PooledStringBuilder.GetInstance() Dim builder = pooledBuilder.Builder builder.Append("(Of ") Dim First = True For Each parameter In typeParameterList.Parameters If Not First Then builder.Append(", ") End If builder.Append(parameter.Identifier.Text) First = False Next builder.Append(")"c) Return pooledBuilder.ToStringAndFree() End Function ''' <summary> ''' Builds up the suffix to show for something with parameters in navigate-to. ''' While it would be nice to just use the compiler SymbolDisplay API for this, ''' it would be too expensive as it requires going back to Symbols (which requires ''' creating compilations, etc.) in a perf sensitive area. ''' ''' So, instead, we just build a reasonable suffix using the pure syntax that a ''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll ''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is ''' actually what the user wrote, And it saves us from ever having to go back to ''' symbols/compilations, this Is well worth it, even if it does mean we have to ''' create our own 'symbol display' logic here. ''' </summary> Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then Return "()" End If Dim pooledBuilder = PooledStringBuilder.GetInstance() Dim builder = pooledBuilder.Builder builder.Append("("c) If parameterList IsNot Nothing Then AppendParameters(parameterList.Parameters, builder) End If builder.Append(")"c) Return pooledBuilder.ToStringAndFree() End Function Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder) Dim First = True For Each parameter In parameters If Not First Then builder.Append(", ") End If For Each modifier In parameter.Modifiers If modifier.Kind() <> SyntaxKind.ByValKeyword Then builder.Append(modifier.Text) builder.Append(" "c) End If Next If parameter.AsClause?.Type IsNot Nothing Then AppendTokens(parameter.AsClause.Type, builder) End If First = False Next End Sub Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String Dim funcDecl = DirectCast(node, MethodStatementSyntax) Debug.Assert(IsExtensionMethod(funcDecl)) Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text) Dim targetTypeName As String = Nothing Dim isArray As Boolean = False TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray) Return CreateReceiverTypeString(targetTypeName, isArray) End Function Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean Dim builder = ArrayBuilder(Of (String, String)).GetInstance() If importStatement IsNot Nothing Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) Dim aliasName, name As String #Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value If simpleImportsClause.Alias IsNot Nothing AndAlso TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then #Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value builder.Add((aliasName, name)) End If End If Next aliases = builder.ToImmutableAndFree() Return True End If aliases = Nothing Return False End Function Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean isArray = False If TypeOf node Is IdentifierNameSyntax Then Dim identifierName = DirectCast(node, IdentifierNameSyntax) Dim text = identifierName.Identifier.Text simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text) Return simpleTypeName IsNot Nothing ElseIf TypeOf node Is ArrayTypeSyntax Then isArray = True Dim arrayType = DirectCast(node, ArrayTypeSyntax) Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing) ElseIf TypeOf node Is GenericNameSyntax Then Dim genericName = DirectCast(node, GenericNameSyntax) Dim name = genericName.Identifier.Text Dim arity = genericName.Arity simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity)) Return True ElseIf TypeOf node Is QualifiedNameSyntax Then ' For an identifier to the right of a '.', it can't be a type parameter, ' so we don't need to check for it further. Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing) ElseIf TypeOf node Is NullableTypeSyntax Then Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray) ElseIf TypeOf node Is PredefinedTypeSyntax Then simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax)) Return simpleTypeName IsNot Nothing ElseIf TypeOf node Is TupleTypeSyntax Then Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count simpleTypeName = CreateValueTupleTypeString(tupleArity) Return True End If simpleTypeName = Nothing Return False End Function Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String Select Case predefinedTypeNode.Keyword.Kind() Case SyntaxKind.BooleanKeyword Return "Boolean" Case SyntaxKind.ByteKeyword Return "Byte" Case SyntaxKind.CharKeyword Return "Char" Case SyntaxKind.DateKeyword Return "DateTime" Case SyntaxKind.DecimalKeyword Return "Decimal" Case SyntaxKind.DoubleKeyword Return "Double" Case SyntaxKind.IntegerKeyword Return "Int32" Case SyntaxKind.LongKeyword Return "Int64" Case SyntaxKind.ObjectKeyword Return "Object" Case SyntaxKind.SByteKeyword Return "SByte" Case SyntaxKind.ShortKeyword Return "Int16" Case SyntaxKind.SingleKeyword Return "Single" Case SyntaxKind.StringKeyword Return "String" Case SyntaxKind.UIntegerKeyword Return "UInt32" Case SyntaxKind.ULongKeyword Return "UInt64" Case SyntaxKind.UShortKeyword Return "UInt16" Case Else Return Nothing End Select End Function Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace 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.Text Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.FindSymbols <ExportLanguageService(GetType(IDeclaredSymbolInfoFactoryService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicDeclaredSymbolInfoFactoryService Inherits AbstractDeclaredSymbolInfoFactoryService(Of CompilationUnitSyntax, ImportsStatementSyntax, NamespaceBlockSyntax, TypeBlockSyntax, EnumBlockSyntax, StatementSyntax, NameSyntax, QualifiedNameSyntax, IdentifierNameSyntax) Private Const ExtensionName As String = "Extension" Private Const ExtensionAttributeName As String = "ExtensionAttribute" <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Private Shared Function GetInheritanceNames(stringTable As StringTable, typeBlock As TypeBlockSyntax) As ImmutableArray(Of String) Dim builder = ArrayBuilder(Of String).GetInstance() Dim aliasMap = GetAliasMap(typeBlock) Try For Each inheritsStatement In typeBlock.Inherits AddInheritanceNames(builder, inheritsStatement.Types, aliasMap) Next For Each implementsStatement In typeBlock.Implements AddInheritanceNames(builder, implementsStatement.Types, aliasMap) Next Intern(stringTable, builder) Return builder.ToImmutableAndFree() Finally FreeAliasMap(aliasMap) End Try End Function Private Shared Function GetAliasMap(typeBlock As TypeBlockSyntax) As Dictionary(Of String, String) Dim compilationUnit = typeBlock.SyntaxTree.GetCompilationUnitRoot() Dim aliasMap As Dictionary(Of String, String) = Nothing For Each import In compilationUnit.Imports For Each clause In import.ImportsClauses If clause.IsKind(SyntaxKind.SimpleImportsClause) Then Dim simpleImport = DirectCast(clause, SimpleImportsClauseSyntax) If simpleImport.Alias IsNot Nothing Then Dim mappedName = GetTypeName(simpleImport.Name) If mappedName IsNot Nothing Then aliasMap = If(aliasMap, AllocateAliasMap()) aliasMap(simpleImport.Alias.Identifier.ValueText) = mappedName End If End If End If Next Next Return aliasMap End Function Private Shared Sub AddInheritanceNames( builder As ArrayBuilder(Of String), types As SeparatedSyntaxList(Of TypeSyntax), aliasMap As Dictionary(Of String, String)) For Each typeSyntax In types AddInheritanceName(builder, typeSyntax, aliasMap) Next End Sub Private Shared Sub AddInheritanceName( builder As ArrayBuilder(Of String), typeSyntax As TypeSyntax, aliasMap As Dictionary(Of String, String)) Dim name = GetTypeName(typeSyntax) If name IsNot Nothing Then builder.Add(name) Dim mappedName As String = Nothing If aliasMap?.TryGetValue(name, mappedName) = True Then ' Looks Like this could be an alias. Also include the name the alias points to builder.Add(mappedName) End If End If End Sub Private Shared Function GetTypeName(typeSyntax As TypeSyntax) As String If TypeOf typeSyntax Is SimpleNameSyntax Then Return GetSimpleName(DirectCast(typeSyntax, SimpleNameSyntax)) ElseIf TypeOf typeSyntax Is QualifiedNameSyntax Then Return GetSimpleName(DirectCast(typeSyntax, QualifiedNameSyntax).Right) End If Return Nothing End Function Private Shared Function GetSimpleName(simpleName As SimpleNameSyntax) As String Return simpleName.Identifier.ValueText End Function Protected Overrides Function GetContainerDisplayName(node As StatementSyntax) As String Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters) End Function Protected Overrides Function GetFullyQualifiedContainerName(node As StatementSyntax, rootNamespace As String) As String Return VisualBasicSyntaxFacts.Instance.GetDisplayName(node, DisplayNameOptions.IncludeNamespaces, rootNamespace) End Function Protected Overrides Sub AddDeclaredSymbolInfosWorker( container As SyntaxNode, node As StatementSyntax, stringTable As StringTable, declaredSymbolInfos As ArrayBuilder(Of DeclaredSymbolInfo), aliases As Dictionary(Of String, String), extensionMethodInfo As Dictionary(Of String, ArrayBuilder(Of Integer)), containerDisplayName As String, fullyQualifiedContainerName As String, cancellationToken As CancellationToken) ' If this Is a part of partial type that only contains nested types, then we don't make an info type for it. ' That's because we effectively think of this as just being a virtual container just to hold the nested ' types, And Not something someone would want to explicitly navigate to itself. Similar to how we think of ' namespaces. Dim typeDecl = TryCast(node, TypeBlockSyntax) If typeDecl IsNot Nothing AndAlso typeDecl.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) AndAlso typeDecl.Members.Any() AndAlso typeDecl.Members.All(Function(m) TypeOf m Is TypeBlockSyntax) Then Return End If If node.Kind() = SyntaxKind.PropertyBlock Then node = DirectCast(node, PropertyBlockSyntax).PropertyStatement ElseIf node.Kind() = SyntaxKind.EventBlock Then node = DirectCast(node, EventBlockSyntax).EventStatement ElseIf TypeOf node Is MethodBlockBaseSyntax Then node = DirectCast(node, MethodBlockBaseSyntax).BlockStatement End If Dim kind = node.Kind() Select Case kind Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock Dim typeBlock = CType(node, TypeBlockSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeDecl.BlockStatement.Identifier.ValueText, GetTypeParameterSuffix(typeBlock.BlockStatement.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, typeBlock.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword), If(kind = SyntaxKind.ClassBlock, DeclaredSymbolInfoKind.Class, If(kind = SyntaxKind.InterfaceBlock, DeclaredSymbolInfoKind.Interface, If(kind = SyntaxKind.ModuleBlock, DeclaredSymbolInfoKind.Module, DeclaredSymbolInfoKind.Struct))), GetAccessibility(container, typeBlock, typeBlock.BlockStatement.Modifiers), typeBlock.BlockStatement.Identifier.Span, GetInheritanceNames(stringTable, typeBlock), IsNestedType(typeBlock))) Return Case SyntaxKind.EnumBlock Dim enumDecl = DirectCast(node, EnumBlockSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumDecl.EnumStatement.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, enumDecl.EnumStatement.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Enum, GetAccessibility(container, enumDecl, enumDecl.EnumStatement.Modifiers), enumDecl.EnumStatement.Identifier.Span, ImmutableArray(Of String).Empty, IsNestedType(enumDecl))) Return Case SyntaxKind.SubNewStatement Dim constructor = DirectCast(node, SubNewStatementSyntax) Dim typeBlock = TryCast(container, TypeBlockSyntax) If typeBlock IsNot Nothing Then declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, typeBlock.BlockStatement.Identifier.ValueText, GetConstructorSuffix(constructor), containerDisplayName, fullyQualifiedContainerName, constructor.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Constructor, GetAccessibility(container, constructor, constructor.Modifiers), constructor.NewKeyword.Span, ImmutableArray(Of String).Empty, parameterCount:=If(constructor.ParameterList?.Parameters.Count, 0))) Return End If Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Dim delegateDecl = DirectCast(node, DelegateStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, delegateDecl.Identifier.ValueText, GetTypeParameterSuffix(delegateDecl.TypeParameterList), containerDisplayName, fullyQualifiedContainerName, delegateDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Delegate, GetAccessibility(container, delegateDecl, delegateDecl.Modifiers), delegateDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.EnumMemberDeclaration Dim enumMember = DirectCast(node, EnumMemberDeclarationSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, enumMember.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, isPartial:=False, DeclaredSymbolInfoKind.EnumMember, Accessibility.Public, enumMember.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.EventStatement Dim eventDecl = DirectCast(node, EventStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, eventDecl.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, eventDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Event, GetAccessibility(container, eventDecl, eventDecl.Modifiers), eventDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement Dim funcDecl = DirectCast(node, MethodStatementSyntax) Dim isExtension = IsExtensionMethod(funcDecl) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, funcDecl.Identifier.ValueText, GetMethodSuffix(funcDecl), containerDisplayName, fullyQualifiedContainerName, funcDecl.Modifiers.Any(SyntaxKind.PartialKeyword), If(isExtension, DeclaredSymbolInfoKind.ExtensionMethod, DeclaredSymbolInfoKind.Method), GetAccessibility(container, funcDecl, funcDecl.Modifiers), funcDecl.Identifier.Span, ImmutableArray(Of String).Empty, parameterCount:=If(funcDecl.ParameterList?.Parameters.Count, 0), typeParameterCount:=If(funcDecl.TypeParameterList?.Parameters.Count, 0))) If isExtension Then AddExtensionMethodInfo(funcDecl, aliases, declaredSymbolInfos.Count - 1, extensionMethodInfo) End If Return Case SyntaxKind.PropertyStatement Dim propertyDecl = DirectCast(node, PropertyStatementSyntax) declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, propertyDecl.Identifier.ValueText, GetPropertySuffix(propertyDecl), containerDisplayName, fullyQualifiedContainerName, propertyDecl.Modifiers.Any(SyntaxKind.PartialKeyword), DeclaredSymbolInfoKind.Property, GetAccessibility(container, propertyDecl, propertyDecl.Modifiers), propertyDecl.Identifier.Span, ImmutableArray(Of String).Empty)) Return Case SyntaxKind.FieldDeclaration Dim fieldDecl = DirectCast(node, FieldDeclarationSyntax) For Each variableDeclarator In fieldDecl.Declarators For Each modifiedIdentifier In variableDeclarator.Names declaredSymbolInfos.Add(DeclaredSymbolInfo.Create( stringTable, modifiedIdentifier.Identifier.ValueText, Nothing, containerDisplayName, fullyQualifiedContainerName, fieldDecl.Modifiers.Any(SyntaxKind.PartialKeyword), If(fieldDecl.Modifiers.Any(Function(m) m.Kind() = SyntaxKind.ConstKeyword), DeclaredSymbolInfoKind.Constant, DeclaredSymbolInfoKind.Field), GetAccessibility(container, fieldDecl, fieldDecl.Modifiers), modifiedIdentifier.Identifier.Span, ImmutableArray(Of String).Empty)) Next Next End Select End Sub Protected Overrides Function GetChildren(node As CompilationUnitSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As NamespaceBlockSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As TypeBlockSyntax) As SyntaxList(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetChildren(node As EnumBlockSyntax) As IEnumerable(Of StatementSyntax) Return node.Members End Function Protected Overrides Function GetUsingAliases(node As CompilationUnitSyntax) As SyntaxList(Of ImportsStatementSyntax) Return node.Imports End Function Protected Overrides Function GetUsingAliases(node As NamespaceBlockSyntax) As SyntaxList(Of ImportsStatementSyntax) Return Nothing End Function Protected Overrides Function GetName(node As NamespaceBlockSyntax) As NameSyntax Return node.NamespaceStatement.Name End Function Protected Overrides Function GetLeft(node As QualifiedNameSyntax) As NameSyntax Return node.Left End Function Protected Overrides Function GetRight(node As QualifiedNameSyntax) As NameSyntax Return node.Right End Function Protected Overrides Function GetIdentifier(node As IdentifierNameSyntax) As SyntaxToken Return node.Identifier End Function Private Shared Function IsExtensionMethod(node As MethodStatementSyntax) As Boolean Dim parameterCount = node.ParameterList?.Parameters.Count ' Extension method must have at least one parameter and declared inside a module If Not parameterCount.HasValue OrElse parameterCount.Value = 0 OrElse TypeOf node.Parent?.Parent IsNot ModuleBlockSyntax Then Return False End If For Each attributeList In node.AttributeLists For Each attribute In attributeList.Attributes ' ExtensionAttribute takes no argument. If attribute.ArgumentList?.Arguments.Count > 0 Then Continue For End If Dim name = attribute.Name.GetRightmostName()?.ToString() If String.Equals(name, ExtensionName, StringComparison.OrdinalIgnoreCase) OrElse String.Equals(name, ExtensionAttributeName, StringComparison.OrdinalIgnoreCase) Then Return True End If Next Next Return False End Function Private Shared Function IsNestedType(node As DeclarationStatementSyntax) As Boolean Return TypeOf node.Parent Is TypeBlockSyntax End Function Private Shared Function GetAccessibility(container As SyntaxNode, node As StatementSyntax, modifiers As SyntaxTokenList) As Accessibility Dim sawFriend = False For Each modifier In modifiers Select Case modifier.Kind() Case SyntaxKind.PublicKeyword : Return Accessibility.Public Case SyntaxKind.PrivateKeyword : Return Accessibility.Private Case SyntaxKind.ProtectedKeyword : Return Accessibility.Protected Case SyntaxKind.FriendKeyword sawFriend = True Continue For End Select Next If sawFriend Then Return Accessibility.Internal End If ' No accessibility modifiers Select Case container.Kind() Case SyntaxKind.ClassBlock ' In a class, fields and shared-constructors are private by default, ' everything Else Is Public If node.Kind() = SyntaxKind.FieldDeclaration Then Return Accessibility.Private End If If node.Kind() = SyntaxKind.SubNewStatement AndAlso DirectCast(node, SubNewStatementSyntax).Modifiers.Any(SyntaxKind.SharedKeyword) Then Return Accessibility.Private End If Return Accessibility.Public Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock ' Everything in a struct/interface/module is public Return Accessibility.Public End Select ' Otherwise, it's internal Return Accessibility.Internal End Function Private Shared Function GetMethodSuffix(method As MethodStatementSyntax) As String Return GetTypeParameterSuffix(method.TypeParameterList) & GetSuffix(method.ParameterList) End Function Private Shared Function GetConstructorSuffix(method As SubNewStatementSyntax) As String Return ".New" & GetSuffix(method.ParameterList) End Function Private Shared Function GetPropertySuffix([property] As PropertyStatementSyntax) As String If [property].ParameterList Is Nothing Then Return Nothing End If Return GetSuffix([property].ParameterList) End Function Private Shared Function GetTypeParameterSuffix(typeParameterList As TypeParameterListSyntax) As String If typeParameterList Is Nothing Then Return Nothing End If Dim pooledBuilder = PooledStringBuilder.GetInstance() Dim builder = pooledBuilder.Builder builder.Append("(Of ") Dim First = True For Each parameter In typeParameterList.Parameters If Not First Then builder.Append(", ") End If builder.Append(parameter.Identifier.Text) First = False Next builder.Append(")"c) Return pooledBuilder.ToStringAndFree() End Function ''' <summary> ''' Builds up the suffix to show for something with parameters in navigate-to. ''' While it would be nice to just use the compiler SymbolDisplay API for this, ''' it would be too expensive as it requires going back to Symbols (which requires ''' creating compilations, etc.) in a perf sensitive area. ''' ''' So, instead, we just build a reasonable suffix using the pure syntax that a ''' user provided. That means that if they wrote "Method(System.Int32 i)" we'll ''' show that as "Method(System.Int32)" Not "Method(Integer)". Given that this Is ''' actually what the user wrote, And it saves us from ever having to go back to ''' symbols/compilations, this Is well worth it, even if it does mean we have to ''' create our own 'symbol display' logic here. ''' </summary> Private Shared Function GetSuffix(parameterList As ParameterListSyntax) As String If parameterList Is Nothing OrElse parameterList.Parameters.Count = 0 Then Return "()" End If Dim pooledBuilder = PooledStringBuilder.GetInstance() Dim builder = pooledBuilder.Builder builder.Append("("c) If parameterList IsNot Nothing Then AppendParameters(parameterList.Parameters, builder) End If builder.Append(")"c) Return pooledBuilder.ToStringAndFree() End Function Private Shared Sub AppendParameters(parameters As SeparatedSyntaxList(Of ParameterSyntax), builder As StringBuilder) Dim First = True For Each parameter In parameters If Not First Then builder.Append(", ") End If For Each modifier In parameter.Modifiers If modifier.Kind() <> SyntaxKind.ByValKeyword Then builder.Append(modifier.Text) builder.Append(" "c) End If Next If parameter.AsClause?.Type IsNot Nothing Then AppendTokens(parameter.AsClause.Type, builder) End If First = False Next End Sub Protected Overrides Function GetReceiverTypeName(node As StatementSyntax) As String Dim funcDecl = DirectCast(node, MethodStatementSyntax) Debug.Assert(IsExtensionMethod(funcDecl)) Dim typeParameterNames = funcDecl.TypeParameterList?.Parameters.SelectAsArray(Function(p) p.Identifier.Text) Dim targetTypeName As String = Nothing Dim isArray As Boolean = False TryGetSimpleTypeNameWorker(funcDecl.ParameterList.Parameters(0).AsClause?.Type, typeParameterNames, targetTypeName, isArray) Return CreateReceiverTypeString(targetTypeName, isArray) End Function Protected Overrides Function TryGetAliasesFromUsingDirective(importStatement As ImportsStatementSyntax, ByRef aliases As ImmutableArray(Of (aliasName As String, name As String))) As Boolean Dim builder = ArrayBuilder(Of (String, String)).GetInstance() If importStatement IsNot Nothing Then For Each importsClause In importStatement.ImportsClauses If importsClause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(importsClause, SimpleImportsClauseSyntax) Dim aliasName, name As String #Disable Warning BC42030 ' Variable is passed by reference before it has been assigned a value If simpleImportsClause.Alias IsNot Nothing AndAlso TryGetSimpleTypeNameWorker(simpleImportsClause.Alias, Nothing, aliasName, Nothing) AndAlso TryGetSimpleTypeNameWorker(simpleImportsClause, Nothing, name, Nothing) Then #Enable Warning BC42030 ' Variable is passed by reference before it has been assigned a value builder.Add((aliasName, name)) End If End If Next aliases = builder.ToImmutableAndFree() Return True End If aliases = Nothing Return False End Function Private Shared Function TryGetSimpleTypeNameWorker(node As SyntaxNode, typeParameterNames As ImmutableArray(Of String)?, ByRef simpleTypeName As String, ByRef isArray As Boolean) As Boolean isArray = False If TypeOf node Is IdentifierNameSyntax Then Dim identifierName = DirectCast(node, IdentifierNameSyntax) Dim text = identifierName.Identifier.Text simpleTypeName = If(typeParameterNames?.Contains(text), Nothing, text) Return simpleTypeName IsNot Nothing ElseIf TypeOf node Is ArrayTypeSyntax Then isArray = True Dim arrayType = DirectCast(node, ArrayTypeSyntax) Return TryGetSimpleTypeNameWorker(arrayType.ElementType, typeParameterNames, simpleTypeName, Nothing) ElseIf TypeOf node Is GenericNameSyntax Then Dim genericName = DirectCast(node, GenericNameSyntax) Dim name = genericName.Identifier.Text Dim arity = genericName.Arity simpleTypeName = If(arity = 0, name, name + ArityUtilities.GetMetadataAritySuffix(arity)) Return True ElseIf TypeOf node Is QualifiedNameSyntax Then ' For an identifier to the right of a '.', it can't be a type parameter, ' so we don't need to check for it further. Dim qualifiedName = DirectCast(node, QualifiedNameSyntax) Return TryGetSimpleTypeNameWorker(qualifiedName.Right, Nothing, simpleTypeName, Nothing) ElseIf TypeOf node Is NullableTypeSyntax Then Return TryGetSimpleTypeNameWorker(DirectCast(node, NullableTypeSyntax).ElementType, typeParameterNames, simpleTypeName, isArray) ElseIf TypeOf node Is PredefinedTypeSyntax Then simpleTypeName = GetSpecialTypeName(DirectCast(node, PredefinedTypeSyntax)) Return simpleTypeName IsNot Nothing ElseIf TypeOf node Is TupleTypeSyntax Then Dim tupleArity = DirectCast(node, TupleTypeSyntax).Elements.Count simpleTypeName = CreateValueTupleTypeString(tupleArity) Return True End If simpleTypeName = Nothing Return False End Function Private Shared Function GetSpecialTypeName(predefinedTypeNode As PredefinedTypeSyntax) As String Select Case predefinedTypeNode.Keyword.Kind() Case SyntaxKind.BooleanKeyword Return "Boolean" Case SyntaxKind.ByteKeyword Return "Byte" Case SyntaxKind.CharKeyword Return "Char" Case SyntaxKind.DateKeyword Return "DateTime" Case SyntaxKind.DecimalKeyword Return "Decimal" Case SyntaxKind.DoubleKeyword Return "Double" Case SyntaxKind.IntegerKeyword Return "Int32" Case SyntaxKind.LongKeyword Return "Int64" Case SyntaxKind.ObjectKeyword Return "Object" Case SyntaxKind.SByteKeyword Return "SByte" Case SyntaxKind.ShortKeyword Return "Int16" Case SyntaxKind.SingleKeyword Return "Single" Case SyntaxKind.StringKeyword Return "String" Case SyntaxKind.UIntegerKeyword Return "UInt32" Case SyntaxKind.ULongKeyword Return "UInt64" Case SyntaxKind.UShortKeyword Return "UInt16" Case Else Return Nothing End Select End Function Protected Overrides Function GetRootNamespace(compilationOptions As CompilationOptions) As String Return DirectCast(compilationOptions, VisualBasicCompilationOptions).RootNamespace End Function End Class End Namespace
1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/InterfaceImplementationCallFinder.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class InterfaceImplementationCallFinder : AbstractCallFinder { private readonly string _text; public InterfaceImplementationCallFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { _text = string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, symbol.ToDisplayString()); } public override string DisplayName => _text; public override string SearchCategory => CallHierarchyPredefinedSearchCategoryNames.InterfaceImplementations; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return calls.Where(c => c.IsDirect); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class InterfaceImplementationCallFinder : AbstractCallFinder { private readonly string _text; public InterfaceImplementationCallFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { _text = string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, symbol.ToDisplayString()); } public override string DisplayName => _text; public override string SearchCategory => CallHierarchyPredefinedSearchCategoryNames.InterfaceImplementations; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return calls.Where(c => c.IsDirect); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/CSharp/Impl/Options/Formatting/SpacingViewModel.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; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingSpacingOptionControl.xaml /// </summary> internal class SpacingViewModel : AbstractOptionPreviewViewModel { private const string s_methodPreview = @" class C { //[ void Goo(){ Goo(1); } void Goo(int x){ Goo(); } //] void Goo(int x, int y){ Goo(); } }"; private const string s_bracketPreview = @"class C { void Goo(){ //[ int[] x = new int[10]; //] } }"; private const string s_forDelimiterPreview = @"class C{ void Goo(int x, object y) { //[ for (int i; i < x; i++) { } //] } }"; private const string s_delimiterPreview = @"class C{ void Goo(int x, object y) { //[ this.Goo(x, y); //] } }"; private const string s_castPreview = @"class C{ void Goo(object x) { //[ int y = (int)x; //] } }"; private const string s_expressionPreview = @"class C{ void Goo(int x, object y) { //[ var x = 3; var y = 4; var z = (x * y) - ((y -x) * 3); //] } }"; private const string s_expressionSpacingPreview = @" class c { int Goo(int x, int y) { //[ return x * (x-y); //] } }"; private const string s_declarationSpacingPreview = @"class MyClass { //[ int index = 0; string text = ""Start""; void Method(){ int i = 0; string s = ""Hello""; } //] }"; private const string s_baseColonPreview = @"//[ interface I { } class C : I { } //]"; public SpacingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_method_declarations }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, CSharpVSResources.Insert_space_between_method_name_and_its_opening_parenthesis2, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, CSharpVSResources.Insert_space_within_parameter_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, CSharpVSResources.Insert_space_within_empty_parameter_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_method_calls }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterMethodCallName, CSharpVSResources.Insert_space_between_method_name_and_its_opening_parenthesis1, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, CSharpVSResources.Insert_space_within_argument_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, CSharpVSResources.Insert_space_within_empty_argument_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_other_spacing_options }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, CSharpVSResources.Insert_space_after_keywords_in_control_flow_statements, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinExpressionParentheses, CSharpVSResources.Insert_space_within_parentheses_of_expressions, s_expressionPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinCastParentheses, CSharpVSResources.Insert_space_within_parentheses_of_type_casts, s_castPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinOtherParentheses, CSharpVSResources.Insert_spaces_within_parentheses_of_control_flow_statements, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterCast, CSharpVSResources.Insert_space_after_cast, s_castPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, CSharpVSResources.Ignore_spaces_in_declaration_statements, s_declarationSpacingPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_brackets }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, CSharpVSResources.Insert_space_before_open_square_bracket, s_bracketPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, CSharpVSResources.Insert_space_within_empty_square_brackets, s_bracketPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinSquareBrackets, CSharpVSResources.Insert_spaces_within_square_brackets, s_bracketPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_delimiters }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, CSharpVSResources.Insert_space_after_colon_for_base_or_interface_in_type_declaration, s_baseColonPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterComma, CSharpVSResources.Insert_space_after_comma, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterDot, CSharpVSResources.Insert_space_after_dot, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, CSharpVSResources.Insert_space_after_semicolon_in_for_statement, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, CSharpVSResources.Insert_space_before_colon_for_base_or_interface_in_type_declaration, s_baseColonPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeComma, CSharpVSResources.Insert_space_before_comma, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeDot, CSharpVSResources.Insert_space_before_dot, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, CSharpVSResources.Insert_space_before_semicolon_in_for_statement, s_forDelimiterPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_operators }); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Ignore_spaces_around_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Ignore, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Remove_spaces_before_and_after_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Remove, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Insert_space_before_and_after_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Single, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); } } }
// 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; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingSpacingOptionControl.xaml /// </summary> internal class SpacingViewModel : AbstractOptionPreviewViewModel { private const string s_methodPreview = @" class C { //[ void Goo(){ Goo(1); } void Goo(int x){ Goo(); } //] void Goo(int x, int y){ Goo(); } }"; private const string s_bracketPreview = @"class C { void Goo(){ //[ int[] x = new int[10]; //] } }"; private const string s_forDelimiterPreview = @"class C{ void Goo(int x, object y) { //[ for (int i; i < x; i++) { } //] } }"; private const string s_delimiterPreview = @"class C{ void Goo(int x, object y) { //[ this.Goo(x, y); //] } }"; private const string s_castPreview = @"class C{ void Goo(object x) { //[ int y = (int)x; //] } }"; private const string s_expressionPreview = @"class C{ void Goo(int x, object y) { //[ var x = 3; var y = 4; var z = (x * y) - ((y -x) * 3); //] } }"; private const string s_expressionSpacingPreview = @" class c { int Goo(int x, int y) { //[ return x * (x-y); //] } }"; private const string s_declarationSpacingPreview = @"class MyClass { //[ int index = 0; string text = ""Start""; void Method(){ int i = 0; string s = ""Hello""; } //] }"; private const string s_baseColonPreview = @"//[ interface I { } class C : I { } //]"; public SpacingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_method_declarations }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, CSharpVSResources.Insert_space_between_method_name_and_its_opening_parenthesis2, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, CSharpVSResources.Insert_space_within_parameter_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, CSharpVSResources.Insert_space_within_empty_parameter_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_method_calls }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterMethodCallName, CSharpVSResources.Insert_space_between_method_name_and_its_opening_parenthesis1, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, CSharpVSResources.Insert_space_within_argument_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, CSharpVSResources.Insert_space_within_empty_argument_list_parentheses, s_methodPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_other_spacing_options }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, CSharpVSResources.Insert_space_after_keywords_in_control_flow_statements, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinExpressionParentheses, CSharpVSResources.Insert_space_within_parentheses_of_expressions, s_expressionPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinCastParentheses, CSharpVSResources.Insert_space_within_parentheses_of_type_casts, s_castPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinOtherParentheses, CSharpVSResources.Insert_spaces_within_parentheses_of_control_flow_statements, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterCast, CSharpVSResources.Insert_space_after_cast, s_castPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, CSharpVSResources.Ignore_spaces_in_declaration_statements, s_declarationSpacingPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_brackets }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, CSharpVSResources.Insert_space_before_open_square_bracket, s_bracketPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, CSharpVSResources.Insert_space_within_empty_square_brackets, s_bracketPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceWithinSquareBrackets, CSharpVSResources.Insert_spaces_within_square_brackets, s_bracketPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_delimiters }); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, CSharpVSResources.Insert_space_after_colon_for_base_or_interface_in_type_declaration, s_baseColonPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterComma, CSharpVSResources.Insert_space_after_comma, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterDot, CSharpVSResources.Insert_space_after_dot, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, CSharpVSResources.Insert_space_after_semicolon_in_for_statement, s_forDelimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, CSharpVSResources.Insert_space_before_colon_for_base_or_interface_in_type_declaration, s_baseColonPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeComma, CSharpVSResources.Insert_space_before_comma, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeDot, CSharpVSResources.Insert_space_before_dot, s_delimiterPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, CSharpVSResources.Insert_space_before_semicolon_in_for_statement, s_forDelimiterPreview, this, optionStore)); Items.Add(new HeaderItemViewModel() { Header = CSharpVSResources.Set_spacing_for_operators }); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Ignore_spaces_around_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Ignore, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Remove_spaces_before_and_after_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Remove, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); Items.Add(new RadioButtonViewModel<BinaryOperatorSpacingOptions>(CSharpVSResources.Insert_space_before_and_after_binary_operators, s_expressionSpacingPreview, "binary", BinaryOperatorSpacingOptions.Single, CSharpFormattingOptions.SpacingAroundBinaryOperator, this, OptionStore)); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/VisualBasic/Portable/Formatting/Rules/AlignTokensFormattingRule.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.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class AlignTokensFormattingRule Inherits BaseFormattingRule Friend Const Name As String = "VisualBasic Align Tokens Formatting Rule" Public Sub New() End Sub Public Overrides Sub AddAlignTokensOperationsSlow(operations As List(Of AlignTokensOperation), node As SyntaxNode, ByRef nextOperation As NextAlignTokensOperationAction) nextOperation.Invoke() Dim queryExpression = TryCast(node, QueryExpressionSyntax) If queryExpression IsNot Nothing Then Dim tokens = New List(Of SyntaxToken)() tokens.AddRange(queryExpression.Clauses.Select(Function(q) q.GetFirstToken(includeZeroWidth:=True))) If tokens.Count > 1 Then AddAlignIndentationOfTokensToBaseTokenOperation(operations, queryExpression, tokens(0), tokens.Skip(1)) End If Return 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 Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class AlignTokensFormattingRule Inherits BaseFormattingRule Friend Const Name As String = "VisualBasic Align Tokens Formatting Rule" Public Sub New() End Sub Public Overrides Sub AddAlignTokensOperationsSlow(operations As List(Of AlignTokensOperation), node As SyntaxNode, ByRef nextOperation As NextAlignTokensOperationAction) nextOperation.Invoke() Dim queryExpression = TryCast(node, QueryExpressionSyntax) If queryExpression IsNot Nothing Then Dim tokens = New List(Of SyntaxToken)() tokens.AddRange(queryExpression.Clauses.Select(Function(q) q.GetFirstToken(includeZeroWidth:=True))) If tokens.Count > 1 Then AddAlignIndentationOfTokensToBaseTokenOperation(operations, queryExpression, tokens(0), tokens.Skip(1)) End If Return End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ObjectCreationExpressionExtensions.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.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module ObjectCreationExpressionExtensions <Extension> Public Function CanRemoveEmptyArgumentList(objectCreationExpression As ObjectCreationExpressionSyntax) As Boolean If objectCreationExpression.ArgumentList Is Nothing Then Return False End If If objectCreationExpression.ArgumentList.Arguments.Count > 0 Then Return False End If Dim nextToken = objectCreationExpression.GetLastToken.GetNextToken() If nextToken.IsKindOrHasMatchingText(SyntaxKind.OpenParenToken) Then Return False End If If nextToken.IsKindOrHasMatchingText(SyntaxKind.DotToken) Then If Not TypeOf objectCreationExpression.Type Is PredefinedTypeSyntax Then Return False End If End If Return True End Function 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. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module ObjectCreationExpressionExtensions <Extension> Public Function CanRemoveEmptyArgumentList(objectCreationExpression As ObjectCreationExpressionSyntax) As Boolean If objectCreationExpression.ArgumentList Is Nothing Then Return False End If If objectCreationExpression.ArgumentList.Arguments.Count > 0 Then Return False End If Dim nextToken = objectCreationExpression.GetLastToken.GetNextToken() If nextToken.IsKindOrHasMatchingText(SyntaxKind.OpenParenToken) Then Return False End If If nextToken.IsKindOrHasMatchingText(SyntaxKind.DotToken) Then If Not TypeOf objectCreationExpression.Type Is PredefinedTypeSyntax Then Return False End If End If Return True End Function End Module End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/IOperation/AssemblyAttributes.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 Xunit
' 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 Xunit
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IfStatement.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIfStatement(BoundIfStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitStatement(node.Consequence); Debug.Assert(rewrittenConsequence is { }); var rewrittenAlternative = VisitStatement(node.AlternativeOpt); var syntax = (IfStatementSyntax)node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (this.Instrument && !node.WasCompilerGenerated) { rewrittenCondition = _instrumenter.InstrumentIfStatementCondition(node, rewrittenCondition, _factory); } var result = RewriteIfStatement(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.HasErrors); // add sequence point before the whole statement if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentIfStatement(node, result); } return result; } private static BoundStatement RewriteIfStatement( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundStatement rewrittenConsequence, BoundStatement? rewrittenAlternativeOpt, bool hasErrors) { var afterif = new GeneratedLabelSymbol("afterif"); var builder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenAlternativeOpt == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, afterif)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); var statements = builder.ToImmutableAndFree(); return new BoundStatementList(syntax, statements, hasErrors); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: var alt = new GeneratedLabelSymbol("alternative"); builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, alt)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundGotoStatement(syntax, afterif)); builder.Add(new BoundLabelStatement(syntax, alt)); builder.Add(rewrittenAlternativeOpt); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); return new BoundStatementList(syntax, builder.ToImmutableAndFree(), hasErrors); } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIfStatement(BoundIfStatement node) { Debug.Assert(node != null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitStatement(node.Consequence); Debug.Assert(rewrittenConsequence is { }); var rewrittenAlternative = VisitStatement(node.AlternativeOpt); var syntax = (IfStatementSyntax)node.Syntax; // EnC: We need to insert a hidden sequence point to handle function remapping in case // the containing method is edited while methods invoked in the condition are being executed. if (this.Instrument && !node.WasCompilerGenerated) { rewrittenCondition = _instrumenter.InstrumentIfStatementCondition(node, rewrittenCondition, _factory); } var result = RewriteIfStatement(syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.HasErrors); // add sequence point before the whole statement if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentIfStatement(node, result); } return result; } private static BoundStatement RewriteIfStatement( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundStatement rewrittenConsequence, BoundStatement? rewrittenAlternativeOpt, bool hasErrors) { var afterif = new GeneratedLabelSymbol("afterif"); var builder = ArrayBuilder<BoundStatement>.GetInstance(); if (rewrittenAlternativeOpt == null) { // if (condition) // consequence; // // becomes // // GotoIfFalse condition afterif; // consequence; // afterif: builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, afterif)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); var statements = builder.ToImmutableAndFree(); return new BoundStatementList(syntax, statements, hasErrors); } else { // if (condition) // consequence; // else // alternative // // becomes // // GotoIfFalse condition alt; // consequence // goto afterif; // alt: // alternative; // afterif: var alt = new GeneratedLabelSymbol("alternative"); builder.Add(new BoundConditionalGoto(rewrittenCondition.Syntax, rewrittenCondition, false, alt)); builder.Add(rewrittenConsequence); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundGotoStatement(syntax, afterif)); builder.Add(new BoundLabelStatement(syntax, alt)); builder.Add(rewrittenAlternativeOpt); builder.Add(BoundSequencePoint.CreateHidden()); builder.Add(new BoundLabelStatement(syntax, afterif)); return new BoundStatementList(syntax, builder.ToImmutableAndFree(), hasErrors); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Syntax/MethodDeclarationSyntax.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class MethodDeclarationSyntax { public int Arity { get { return this.TypeParameterList == null ? 0 : this.TypeParameterList.Parameters.Count; } } } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static MethodDeclarationSyntax MethodDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.MethodDeclaration( attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, null, semicolonToken); } } }
// 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class MethodDeclarationSyntax { public int Arity { get { return this.TypeParameterList == null ? 0 : this.TypeParameterList.Parameters.Count; } } } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static MethodDeclarationSyntax MethodDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax body, SyntaxToken semicolonToken) { return SyntaxFactory.MethodDeclaration( attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, null, semicolonToken); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/CSharp/Portable/UseExpressionBodyForLambda/UseExpressionBodyForLambdaCodeStyleProvider_Analysis.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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the DiagnosticAnalyzer ("Analysis") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override void DiagnosticAnalyzerInitialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression); protected override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption2<ExpressionBodyPreference> option) { var declaration = (LambdaExpressionSyntax)context.Node; var diagnostic = AnalyzeSyntax(context.SemanticModel, option, declaration, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic AnalyzeSyntax( SemanticModel semanticModel, CodeStyleOption2<ExpressionBodyPreference> option, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { if (CanOfferUseExpressionBody(option.Value, declaration)) { var location = GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty; return DiagnosticHelper.Create( CreateDescriptorWithId(UseExpressionBodyTitle, UseExpressionBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } if (CanOfferUseBlockBody(semanticModel, option.Value, declaration, cancellationToken)) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = GetDiagnosticLocation(declaration); var properties = ImmutableDictionary<string, string>.Empty; var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(UseBlockBodyTitle, UseBlockBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } return null; } private static Location GetDiagnosticLocation(LambdaExpressionSyntax declaration) => Location.Create(declaration.SyntaxTree, TextSpan.FromBounds(declaration.SpanStart, declaration.ArrowToken.Span.End)); } }
// 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.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBodyForLambda { // Code for the DiagnosticAnalyzer ("Analysis") portion of the feature. internal partial class UseExpressionBodyForLambdaCodeStyleProvider { protected override void DiagnosticAnalyzerInitialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SimpleLambdaExpression, SyntaxKind.ParenthesizedLambdaExpression); protected override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, CodeStyleOption2<ExpressionBodyPreference> option) { var declaration = (LambdaExpressionSyntax)context.Node; var diagnostic = AnalyzeSyntax(context.SemanticModel, option, declaration, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic AnalyzeSyntax( SemanticModel semanticModel, CodeStyleOption2<ExpressionBodyPreference> option, LambdaExpressionSyntax declaration, CancellationToken cancellationToken) { if (CanOfferUseExpressionBody(option.Value, declaration)) { var location = GetDiagnosticLocation(declaration); var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); var properties = ImmutableDictionary<string, string>.Empty; return DiagnosticHelper.Create( CreateDescriptorWithId(UseExpressionBodyTitle, UseExpressionBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } if (CanOfferUseBlockBody(semanticModel, option.Value, declaration, cancellationToken)) { // They have an expression body. Create a diagnostic to convert it to a block // if they don't want expression bodies for this member. var location = GetDiagnosticLocation(declaration); var properties = ImmutableDictionary<string, string>.Empty; var additionalLocations = ImmutableArray.Create(declaration.GetLocation()); return DiagnosticHelper.Create( CreateDescriptorWithId(UseBlockBodyTitle, UseBlockBodyTitle), location, option.Notification.Severity, additionalLocations, properties); } return null; } private static Location GetDiagnosticLocation(LambdaExpressionSyntax declaration) => Location.Create(declaration.SyntaxTree, TextSpan.FromBounds(declaration.SpanStart, declaration.ArrowToken.Span.End)); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/Symbols/IFieldSymbol.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.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a field in a class, struct or enum. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IFieldSymbol : ISymbol { /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> bool IsFixedSizeBuffer { get; } /// <summary> /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. /// If IsFixedSizeBuffer is false or there is an error (such as a bad constant value in source), FixedSize is 0. /// Note that for fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> int FixedSize { get; } /// <summary> /// Gets the type of this field. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this field. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> [MemberNotNullWhen(true, nameof(ConstantValue))] bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this field /// </summary> object? ConstantValue { get; } /// <summary> /// Returns custom modifiers associated with the field, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> CustomModifiers { get; } /// <summary> /// Get the original definition of this symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new IFieldSymbol OriginalDefinition { get; } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> /// <remarks> /// A tuple type will always have default elements such as Item1, Item2, Item3... /// This API allows matching a field that represents a named element, such as "Alice" /// to the corresponding default element field such as "Item1" /// </remarks> IFieldSymbol? CorrespondingTupleField { get; } /// <summary> /// Returns true if this field represents a tuple element which was given an explicit name. /// </summary> bool IsExplicitlyNamedTupleElement { 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.Collections.Immutable; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a field in a class, struct or enum. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IFieldSymbol : ISymbol { /// <summary> /// If this field serves as a backing variable for an automatically generated /// property or a field-like event, returns that /// property/event. Otherwise returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Returns true if this field was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this field was declared as "readonly". /// </summary> bool IsReadOnly { get; } /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } /// <summary> /// Returns true if this field was declared as "fixed". /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> bool IsFixedSizeBuffer { get; } /// <summary> /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. /// If IsFixedSizeBuffer is false or there is an error (such as a bad constant value in source), FixedSize is 0. /// Note that for fixed-size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// </summary> int FixedSize { get; } /// <summary> /// Gets the type of this field. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this field. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns false if the field wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> [MemberNotNullWhen(true, nameof(ConstantValue))] bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this field /// </summary> object? ConstantValue { get; } /// <summary> /// Returns custom modifiers associated with the field, or an empty array if there are none. /// </summary> ImmutableArray<CustomModifier> CustomModifiers { get; } /// <summary> /// Get the original definition of this symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new IFieldSymbol OriginalDefinition { get; } /// <summary> /// If this field represents a tuple element, returns a corresponding default element field. /// Otherwise returns null. /// </summary> /// <remarks> /// A tuple type will always have default elements such as Item1, Item2, Item3... /// This API allows matching a field that represents a named element, such as "Alice" /// to the corresponding default element field such as "Item1" /// </remarks> IFieldSymbol? CorrespondingTupleField { get; } /// <summary> /// Returns true if this field represents a tuple element which was given an explicit name. /// </summary> bool IsExplicitlyNamedTupleElement { get; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Symbols/Source/TypeParameterConstraintClause.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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { [Flags] internal enum TypeParameterConstraintKind { None = 0x00, ReferenceType = 0x01, ValueType = 0x02, Constructor = 0x04, Unmanaged = 0x08, NullableReferenceType = ReferenceType | 0x10, NotNullableReferenceType = ReferenceType | 0x20, /// <summary> /// Type parameter has no type constraints, including `struct`, `class`, `unmanaged` and is declared in a context /// where nullable annotations are disabled. /// Cannot be combined with <see cref="ReferenceType"/>, <see cref="ValueType"/> or <see cref="Unmanaged"/>. /// Note, presence of this flag suppresses generation of Nullable attribute on the corresponding type parameter. /// This imitates the shape of metadata produced by pre-nullable compilers. Metadata import is adjusted accordingly /// to distinguish between the two situations. /// </summary> ObliviousNullabilityIfReferenceType = 0x40, NotNull = 0x80, Default = 0x100, /// <summary> /// <see cref="TypeParameterConstraintKind"/> mismatch is detected during merging process for partial type declarations. /// </summary> PartialMismatch = 0x200, ValueTypeFromConstraintTypes = 0x400, // Not set if any flag from AllValueTypeKinds is set ReferenceTypeFromConstraintTypes = 0x800, /// <summary> /// All bits involved into describing various aspects of 'class' constraint. /// </summary> AllReferenceTypeKinds = NullableReferenceType | NotNullableReferenceType, /// <summary> /// Any of these bits is equivalent to presence of 'struct' constraint. /// </summary> AllValueTypeKinds = ValueType | Unmanaged, /// <summary> /// All bits except those that are involved into describing various nullability aspects. /// </summary> AllNonNullableKinds = ReferenceType | ValueType | Constructor | Unmanaged, } /// <summary> /// A simple representation of a type parameter constraint clause /// as a set of constraint bits and a set of constraint types. /// </summary> internal sealed class TypeParameterConstraintClause { internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause( TypeParameterConstraintKind.None, ImmutableArray<TypeWithAnnotations>.Empty); internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause( TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, ImmutableArray<TypeWithAnnotations>.Empty); internal static TypeParameterConstraintClause Create( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefault); if (constraintTypes.IsEmpty) { switch (constraints) { case TypeParameterConstraintKind.None: return Empty; case TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType: return ObliviousNullabilityIfReferenceType; } } return new TypeParameterConstraintClause(constraints, constraintTypes); } private TypeParameterConstraintClause( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { #if DEBUG switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.None: case TypeParameterConstraintKind.ReferenceType: case TypeParameterConstraintKind.NullableReferenceType: case TypeParameterConstraintKind.NotNullableReferenceType: break; default: ExceptionUtilities.UnexpectedValue(constraints); // This call asserts. break; } Debug.Assert((constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default | TypeParameterConstraintKind.PartialMismatch | TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); #endif this.Constraints = constraints; this.ConstraintTypes = constraintTypes; } public readonly TypeParameterConstraintKind Constraints; public readonly ImmutableArray<TypeWithAnnotations> ConstraintTypes; internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsValueTypeMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isValueTypeMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isValueType(typeParameter, constraintClauses, isValueTypeMap, ConsList<TypeParameterSymbol>.Empty); } return isValueTypeMap; static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isValueTypeMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isValueTypeMap.TryGetValue(thisTypeParameter, out bool knownIsValueType)) { return knownIsValueType; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; if ((constraintClause.Constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0) { result = true; } else { Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter && (object)typeParameter.ContainingSymbol == (object)container) { if (isValueType(typeParameter, constraintClauses, isValueTypeMap, inProgress)) { result = true; break; } } else if (type.IsValueType) { result = true; break; } } } isValueTypeMap.Add(thisTypeParameter, result); return result; } } internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsReferenceTypeFromConstraintTypesMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isReferenceTypeFromConstraintTypesMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol>.Empty); } return isReferenceTypeFromConstraintTypesMap; static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, out bool knownIsReferenceTypeFromConstraintTypes)) { return knownIsReferenceTypeFromConstraintTypes; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter) { if ((object)typeParameter.ContainingSymbol == (object)container) { if (isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, inProgress)) { result = true; break; } } else if (typeParameter.IsReferenceTypeFromConstraintTypes) { result = true; break; } } else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(type)) { result = true; break; } } isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, result); return result; } } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { [Flags] internal enum TypeParameterConstraintKind { None = 0x00, ReferenceType = 0x01, ValueType = 0x02, Constructor = 0x04, Unmanaged = 0x08, NullableReferenceType = ReferenceType | 0x10, NotNullableReferenceType = ReferenceType | 0x20, /// <summary> /// Type parameter has no type constraints, including `struct`, `class`, `unmanaged` and is declared in a context /// where nullable annotations are disabled. /// Cannot be combined with <see cref="ReferenceType"/>, <see cref="ValueType"/> or <see cref="Unmanaged"/>. /// Note, presence of this flag suppresses generation of Nullable attribute on the corresponding type parameter. /// This imitates the shape of metadata produced by pre-nullable compilers. Metadata import is adjusted accordingly /// to distinguish between the two situations. /// </summary> ObliviousNullabilityIfReferenceType = 0x40, NotNull = 0x80, Default = 0x100, /// <summary> /// <see cref="TypeParameterConstraintKind"/> mismatch is detected during merging process for partial type declarations. /// </summary> PartialMismatch = 0x200, ValueTypeFromConstraintTypes = 0x400, // Not set if any flag from AllValueTypeKinds is set ReferenceTypeFromConstraintTypes = 0x800, /// <summary> /// All bits involved into describing various aspects of 'class' constraint. /// </summary> AllReferenceTypeKinds = NullableReferenceType | NotNullableReferenceType, /// <summary> /// Any of these bits is equivalent to presence of 'struct' constraint. /// </summary> AllValueTypeKinds = ValueType | Unmanaged, /// <summary> /// All bits except those that are involved into describing various nullability aspects. /// </summary> AllNonNullableKinds = ReferenceType | ValueType | Constructor | Unmanaged, } /// <summary> /// A simple representation of a type parameter constraint clause /// as a set of constraint bits and a set of constraint types. /// </summary> internal sealed class TypeParameterConstraintClause { internal static readonly TypeParameterConstraintClause Empty = new TypeParameterConstraintClause( TypeParameterConstraintKind.None, ImmutableArray<TypeWithAnnotations>.Empty); internal static readonly TypeParameterConstraintClause ObliviousNullabilityIfReferenceType = new TypeParameterConstraintClause( TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType, ImmutableArray<TypeWithAnnotations>.Empty); internal static TypeParameterConstraintClause Create( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { Debug.Assert(!constraintTypes.IsDefault); if (constraintTypes.IsEmpty) { switch (constraints) { case TypeParameterConstraintKind.None: return Empty; case TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType: return ObliviousNullabilityIfReferenceType; } } return new TypeParameterConstraintClause(constraints, constraintTypes); } private TypeParameterConstraintClause( TypeParameterConstraintKind constraints, ImmutableArray<TypeWithAnnotations> constraintTypes) { #if DEBUG switch (constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) { case TypeParameterConstraintKind.None: case TypeParameterConstraintKind.ReferenceType: case TypeParameterConstraintKind.NullableReferenceType: case TypeParameterConstraintKind.NotNullableReferenceType: break; default: ExceptionUtilities.UnexpectedValue(constraints); // This call asserts. break; } Debug.Assert((constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraints & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor | TypeParameterConstraintKind.Default | TypeParameterConstraintKind.PartialMismatch | TypeParameterConstraintKind.ValueTypeFromConstraintTypes | TypeParameterConstraintKind.ReferenceTypeFromConstraintTypes)) == 0); #endif this.Constraints = constraints; this.ConstraintTypes = constraintTypes; } public readonly TypeParameterConstraintKind Constraints; public readonly ImmutableArray<TypeWithAnnotations> ConstraintTypes; internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsValueTypeMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isValueTypeMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isValueType(typeParameter, constraintClauses, isValueTypeMap, ConsList<TypeParameterSymbol>.Empty); } return isValueTypeMap; static bool isValueType(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isValueTypeMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isValueTypeMap.TryGetValue(thisTypeParameter, out bool knownIsValueType)) { return knownIsValueType; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; if ((constraintClause.Constraints & TypeParameterConstraintKind.AllValueTypeKinds) != 0) { result = true; } else { Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter && (object)typeParameter.ContainingSymbol == (object)container) { if (isValueType(typeParameter, constraintClauses, isValueTypeMap, inProgress)) { result = true; break; } } else if (type.IsValueType) { result = true; break; } } } isValueTypeMap.Add(thisTypeParameter, result); return result; } } internal static SmallDictionary<TypeParameterSymbol, bool> BuildIsReferenceTypeFromConstraintTypesMap(Symbol container, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeParameterConstraintClause> constraintClauses) { Debug.Assert(constraintClauses.Length == typeParameters.Length); var isReferenceTypeFromConstraintTypesMap = new SmallDictionary<TypeParameterSymbol, bool>(ReferenceEqualityComparer.Instance); foreach (TypeParameterSymbol typeParameter in typeParameters) { isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol>.Empty); } return isReferenceTypeFromConstraintTypesMap; static bool isReferenceTypeFromConstraintTypes(TypeParameterSymbol thisTypeParameter, ImmutableArray<TypeParameterConstraintClause> constraintClauses, SmallDictionary<TypeParameterSymbol, bool> isReferenceTypeFromConstraintTypesMap, ConsList<TypeParameterSymbol> inProgress) { if (inProgress.ContainsReference(thisTypeParameter)) { return false; } if (isReferenceTypeFromConstraintTypesMap.TryGetValue(thisTypeParameter, out bool knownIsReferenceTypeFromConstraintTypes)) { return knownIsReferenceTypeFromConstraintTypes; } TypeParameterConstraintClause constraintClause = constraintClauses[thisTypeParameter.Ordinal]; bool result = false; Symbol container = thisTypeParameter.ContainingSymbol; inProgress = inProgress.Prepend(thisTypeParameter); foreach (TypeWithAnnotations constraintType in constraintClause.ConstraintTypes) { TypeSymbol type = constraintType.IsResolved ? constraintType.Type : constraintType.DefaultType; if (type is TypeParameterSymbol typeParameter) { if ((object)typeParameter.ContainingSymbol == (object)container) { if (isReferenceTypeFromConstraintTypes(typeParameter, constraintClauses, isReferenceTypeFromConstraintTypesMap, inProgress)) { result = true; break; } } else if (typeParameter.IsReferenceTypeFromConstraintTypes) { result = true; break; } } else if (TypeParameterSymbol.NonTypeParameterConstraintImpliesReferenceType(type)) { result = true; break; } } isReferenceTypeFromConstraintTypesMap.Add(thisTypeParameter, result); return result; } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Test/Core/Diagnostics/TrackingDiagnosticAnalyzer.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.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public abstract class TrackingDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct { #region Tracking public class Entry { public readonly string AbstractMemberName; public readonly string CallerName; public readonly TLanguageKindEnum SyntaxKind; public readonly SymbolKind? SymbolKind; public readonly MethodKind? MethodKind; public readonly bool ReturnsVoid; public Entry(string abstractMemberName, string callerName, SyntaxNode node, ISymbol symbol) { AbstractMemberName = abstractMemberName; CallerName = callerName; SyntaxKind = node == null ? default(TLanguageKindEnum) : (TLanguageKindEnum)(object)(ushort)node.RawKind; SymbolKind = symbol == null ? (SymbolKind?)null : symbol.Kind; MethodKind = symbol is IMethodSymbol ? ((IMethodSymbol)symbol).MethodKind : (MethodKind?)null; ReturnsVoid = symbol is IMethodSymbol ? ((IMethodSymbol)symbol).ReturnsVoid : false; } public override string ToString() { return CallerName + "(" + string.Join(", ", SymbolKind, MethodKind, SyntaxKind) + ")"; } } private readonly ConcurrentQueue<Entry> _callLog = new ConcurrentQueue<Entry>(); protected override void OnAbstractMember(string abstractMemberName, SyntaxNode node, ISymbol symbol, string callerName) { _callLog.Enqueue(new Entry(abstractMemberName, callerName, node, symbol)); } public IEnumerable<Entry> CallLog { get { return _callLog; } } #endregion #region Analysis private static readonly Regex s_omittedSyntaxKindRegex = new Regex(@"None|Trivia|Token|Keyword|List|Xml|Cref|Compilation|Namespace|Class|Struct|Enum|Interface|Delegate|Field|Property|Indexer|Event|Operator|Constructor|Access|Incomplete|Attribute|Filter|InterpolatedString"); private bool FilterByAbstractName(Entry entry, string abstractMemberName) { return abstractMemberName == entry.AbstractMemberName; } public void VerifyAllAnalyzerMembersWereCalled() { var actualMembers = _callLog.Select(e => e.CallerName).Distinct(); AssertSequenceEqual(AllAnalyzerMemberNames, actualMembers); } public void VerifyAnalyzeSymbolCalledForAllSymbolKinds() { var expectedSymbolKinds = new[] { SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Parameter, SymbolKind.Property }; var actualSymbolKinds = _callLog.Where(a => FilterByAbstractName(a, "Symbol")).Where(e => e.SymbolKind.HasValue).Select(e => e.SymbolKind.Value).Distinct(); AssertSequenceEqual(expectedSymbolKinds, actualSymbolKinds); } protected virtual bool IsAnalyzeNodeSupported(TLanguageKindEnum syntaxKind) { return !s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString()); } public void VerifyAnalyzeNodeCalledForAllSyntaxKinds(HashSet<TLanguageKindEnum> expectedMissingSyntaxKinds) { var expectedSyntaxKinds = AllSyntaxKinds.Where(IsAnalyzeNodeSupported); var actualSyntaxKinds = new HashSet<TLanguageKindEnum>(_callLog.Where(a => FilterByAbstractName(a, "SyntaxNode")).Select(e => e.SyntaxKind)); var savedSyntaxKindsPatterns = new HashSet<TLanguageKindEnum>(expectedMissingSyntaxKinds); expectedMissingSyntaxKinds.IntersectWith(actualSyntaxKinds); Assert.True(expectedMissingSyntaxKinds.Count == 0, "AllInOne test contains ignored SyntaxKinds: " + string.Join(", ", expectedMissingSyntaxKinds)); actualSyntaxKinds.UnionWith(savedSyntaxKindsPatterns); AssertIsSuperset(expectedSyntaxKinds, actualSyntaxKinds); } protected virtual bool IsOnCodeBlockSupported(SymbolKind symbolKind, MethodKind methodKind, bool returnsVoid) { return true; } public void VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(HashSet<SymbolKind> symbolKindsWithNoCodeBlocks = null, bool allowUnexpectedCalls = false) { const MethodKind InvalidMethodKind = (MethodKind)(-1); var expectedArguments = new[] { new { SymbolKind = SymbolKind.Event, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Field, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Constructor, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Conversion, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Destructor, ReturnsVoid = true }, // C# only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventAdd, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventRemove, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventRaise, ReturnsVoid = true }, // VB only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.ExplicitInterfaceImplementation, ReturnsVoid = true }, // C# only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Ordinary, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Ordinary, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.PropertyGet, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.PropertySet, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.StaticConstructor, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.UserDefinedOperator, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Property, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.NamedType, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Namespace, MethodKind = InvalidMethodKind, ReturnsVoid = false } }.AsEnumerable(); if (symbolKindsWithNoCodeBlocks != null) { expectedArguments = expectedArguments.Where(a => !symbolKindsWithNoCodeBlocks.Contains(a.SymbolKind)); } expectedArguments = expectedArguments.Where(a => IsOnCodeBlockSupported(a.SymbolKind, a.MethodKind, a.ReturnsVoid)); var actualOnCodeBlockStartedArguments = _callLog.Where(a => FilterByAbstractName(a, "CodeBlockStart")) .Select(e => new { SymbolKind = e.SymbolKind.Value, MethodKind = e.MethodKind ?? InvalidMethodKind, e.ReturnsVoid }).Distinct(); var actualOnCodeBlockEndedArguments = _callLog.Where(a => FilterByAbstractName(a, "CodeBlock")) .Select(e => new { SymbolKind = e.SymbolKind.Value, MethodKind = e.MethodKind ?? InvalidMethodKind, e.ReturnsVoid }).Distinct(); if (!allowUnexpectedCalls) { AssertSequenceEqual(expectedArguments, actualOnCodeBlockStartedArguments, items => items.OrderBy(p => p.SymbolKind).ThenBy(p => p.MethodKind).ThenBy(p => p.ReturnsVoid)); AssertSequenceEqual(expectedArguments, actualOnCodeBlockEndedArguments, items => items.OrderBy(p => p.SymbolKind).ThenBy(p => p.MethodKind).ThenBy(p => p.ReturnsVoid)); } else { AssertIsSuperset(expectedArguments, actualOnCodeBlockStartedArguments); AssertIsSuperset(expectedArguments, actualOnCodeBlockEndedArguments); } } private void AssertSequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, Func<IEnumerable<T>, IOrderedEnumerable<T>> sorter = null) { sorter = sorter ?? new Func<IEnumerable<T>, IOrderedEnumerable<T>>(items => items.OrderBy(i => i)); expected = sorter(expected); actual = sorter(actual); Assert.True(expected.SequenceEqual(actual), Environment.NewLine + "Expected: " + string.Join(", ", expected) + Environment.NewLine + "Actual: " + string.Join(", ", actual)); } private void AssertIsSuperset<T>(IEnumerable<T> expectedSubset, IEnumerable<T> actualSuperset) { var missingElements = expectedSubset.GroupJoin(actualSuperset, e => e, a => a, (e, a) => new { Element = e, IsMissing = !a.Any() }) .Where(p => p.IsMissing).Select(p => p.Element).ToList(); var presentElements = expectedSubset.Except(missingElements); Assert.True(missingElements.Count == 0, Environment.NewLine + "Missing: " + string.Join(", ", missingElements) + Environment.NewLine + "Present: " + string.Join(", ", presentElements)); } #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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities { public abstract class TrackingDiagnosticAnalyzer<TLanguageKindEnum> : TestDiagnosticAnalyzer<TLanguageKindEnum> where TLanguageKindEnum : struct { #region Tracking public class Entry { public readonly string AbstractMemberName; public readonly string CallerName; public readonly TLanguageKindEnum SyntaxKind; public readonly SymbolKind? SymbolKind; public readonly MethodKind? MethodKind; public readonly bool ReturnsVoid; public Entry(string abstractMemberName, string callerName, SyntaxNode node, ISymbol symbol) { AbstractMemberName = abstractMemberName; CallerName = callerName; SyntaxKind = node == null ? default(TLanguageKindEnum) : (TLanguageKindEnum)(object)(ushort)node.RawKind; SymbolKind = symbol == null ? (SymbolKind?)null : symbol.Kind; MethodKind = symbol is IMethodSymbol ? ((IMethodSymbol)symbol).MethodKind : (MethodKind?)null; ReturnsVoid = symbol is IMethodSymbol ? ((IMethodSymbol)symbol).ReturnsVoid : false; } public override string ToString() { return CallerName + "(" + string.Join(", ", SymbolKind, MethodKind, SyntaxKind) + ")"; } } private readonly ConcurrentQueue<Entry> _callLog = new ConcurrentQueue<Entry>(); protected override void OnAbstractMember(string abstractMemberName, SyntaxNode node, ISymbol symbol, string callerName) { _callLog.Enqueue(new Entry(abstractMemberName, callerName, node, symbol)); } public IEnumerable<Entry> CallLog { get { return _callLog; } } #endregion #region Analysis private static readonly Regex s_omittedSyntaxKindRegex = new Regex(@"None|Trivia|Token|Keyword|List|Xml|Cref|Compilation|Namespace|Class|Struct|Enum|Interface|Delegate|Field|Property|Indexer|Event|Operator|Constructor|Access|Incomplete|Attribute|Filter|InterpolatedString"); private bool FilterByAbstractName(Entry entry, string abstractMemberName) { return abstractMemberName == entry.AbstractMemberName; } public void VerifyAllAnalyzerMembersWereCalled() { var actualMembers = _callLog.Select(e => e.CallerName).Distinct(); AssertSequenceEqual(AllAnalyzerMemberNames, actualMembers); } public void VerifyAnalyzeSymbolCalledForAllSymbolKinds() { var expectedSymbolKinds = new[] { SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Parameter, SymbolKind.Property }; var actualSymbolKinds = _callLog.Where(a => FilterByAbstractName(a, "Symbol")).Where(e => e.SymbolKind.HasValue).Select(e => e.SymbolKind.Value).Distinct(); AssertSequenceEqual(expectedSymbolKinds, actualSymbolKinds); } protected virtual bool IsAnalyzeNodeSupported(TLanguageKindEnum syntaxKind) { return !s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString()); } public void VerifyAnalyzeNodeCalledForAllSyntaxKinds(HashSet<TLanguageKindEnum> expectedMissingSyntaxKinds) { var expectedSyntaxKinds = AllSyntaxKinds.Where(IsAnalyzeNodeSupported); var actualSyntaxKinds = new HashSet<TLanguageKindEnum>(_callLog.Where(a => FilterByAbstractName(a, "SyntaxNode")).Select(e => e.SyntaxKind)); var savedSyntaxKindsPatterns = new HashSet<TLanguageKindEnum>(expectedMissingSyntaxKinds); expectedMissingSyntaxKinds.IntersectWith(actualSyntaxKinds); Assert.True(expectedMissingSyntaxKinds.Count == 0, "AllInOne test contains ignored SyntaxKinds: " + string.Join(", ", expectedMissingSyntaxKinds)); actualSyntaxKinds.UnionWith(savedSyntaxKindsPatterns); AssertIsSuperset(expectedSyntaxKinds, actualSyntaxKinds); } protected virtual bool IsOnCodeBlockSupported(SymbolKind symbolKind, MethodKind methodKind, bool returnsVoid) { return true; } public void VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(HashSet<SymbolKind> symbolKindsWithNoCodeBlocks = null, bool allowUnexpectedCalls = false) { const MethodKind InvalidMethodKind = (MethodKind)(-1); var expectedArguments = new[] { new { SymbolKind = SymbolKind.Event, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Field, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Constructor, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Conversion, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Destructor, ReturnsVoid = true }, // C# only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventAdd, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventRemove, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.EventRaise, ReturnsVoid = true }, // VB only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.ExplicitInterfaceImplementation, ReturnsVoid = true }, // C# only new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Ordinary, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.Ordinary, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.PropertyGet, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.PropertySet, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.StaticConstructor, ReturnsVoid = true }, new { SymbolKind = SymbolKind.Method, MethodKind = MethodKind.UserDefinedOperator, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Property, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.NamedType, MethodKind = InvalidMethodKind, ReturnsVoid = false }, new { SymbolKind = SymbolKind.Namespace, MethodKind = InvalidMethodKind, ReturnsVoid = false } }.AsEnumerable(); if (symbolKindsWithNoCodeBlocks != null) { expectedArguments = expectedArguments.Where(a => !symbolKindsWithNoCodeBlocks.Contains(a.SymbolKind)); } expectedArguments = expectedArguments.Where(a => IsOnCodeBlockSupported(a.SymbolKind, a.MethodKind, a.ReturnsVoid)); var actualOnCodeBlockStartedArguments = _callLog.Where(a => FilterByAbstractName(a, "CodeBlockStart")) .Select(e => new { SymbolKind = e.SymbolKind.Value, MethodKind = e.MethodKind ?? InvalidMethodKind, e.ReturnsVoid }).Distinct(); var actualOnCodeBlockEndedArguments = _callLog.Where(a => FilterByAbstractName(a, "CodeBlock")) .Select(e => new { SymbolKind = e.SymbolKind.Value, MethodKind = e.MethodKind ?? InvalidMethodKind, e.ReturnsVoid }).Distinct(); if (!allowUnexpectedCalls) { AssertSequenceEqual(expectedArguments, actualOnCodeBlockStartedArguments, items => items.OrderBy(p => p.SymbolKind).ThenBy(p => p.MethodKind).ThenBy(p => p.ReturnsVoid)); AssertSequenceEqual(expectedArguments, actualOnCodeBlockEndedArguments, items => items.OrderBy(p => p.SymbolKind).ThenBy(p => p.MethodKind).ThenBy(p => p.ReturnsVoid)); } else { AssertIsSuperset(expectedArguments, actualOnCodeBlockStartedArguments); AssertIsSuperset(expectedArguments, actualOnCodeBlockEndedArguments); } } private void AssertSequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, Func<IEnumerable<T>, IOrderedEnumerable<T>> sorter = null) { sorter = sorter ?? new Func<IEnumerable<T>, IOrderedEnumerable<T>>(items => items.OrderBy(i => i)); expected = sorter(expected); actual = sorter(actual); Assert.True(expected.SequenceEqual(actual), Environment.NewLine + "Expected: " + string.Join(", ", expected) + Environment.NewLine + "Actual: " + string.Join(", ", actual)); } private void AssertIsSuperset<T>(IEnumerable<T> expectedSubset, IEnumerable<T> actualSuperset) { var missingElements = expectedSubset.GroupJoin(actualSuperset, e => e, a => a, (e, a) => new { Element = e, IsMissing = !a.Any() }) .Where(p => p.IsMissing).Select(p => p.Element).ToList(); var presentElements = expectedSubset.Except(missingElements); Assert.True(missingElements.Count == 0, Environment.NewLine + "Missing: " + string.Join(", ", missingElements) + Environment.NewLine + "Present: " + string.Join(", ", presentElements)); } #endregion } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/IntegrationTest/TestUtilities/ScreenshotService.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.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using PixelFormats = System.Windows.Media.PixelFormats; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { internal static class ScreenshotService { private static readonly object s_gate = new object(); /// <summary> /// Takes a picture of the screen and saves it to the location specified by /// <paramref name="fullPath"/>. Files are always saved in PNG format, regardless of the /// file extension. /// </summary> public static void TakeScreenshot(string fullPath) { // This gate prevents concurrency for two reasons: // // 1. Only one screenshot is held in memory at a time to prevent running out of memory for large displays // 2. Only one screenshot is written to disk at a time to avoid exceptions if concurrent calls are writing // to the same file lock (s_gate) { var bitmap = TryCaptureFullScreen(); if (bitmap == null) { return; } var directory = Path.GetDirectoryName(fullPath); Directory.CreateDirectory(directory); using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(fileStream); } } } /// <summary> /// Captures the full screen to a <see cref="Bitmap"/>. /// </summary> /// <returns> /// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen /// capture can't be created. /// </returns> private static BitmapSource? TryCaptureFullScreen() { var width = Screen.PrimaryScreen.Bounds.Width; var height = Screen.PrimaryScreen.Bounds.Height; if (width <= 0 || height <= 0) { // Don't try to take a screenshot if there is no screen. // This may not be an interactive session. return null; } using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) using (var graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen( sourceX: Screen.PrimaryScreen.Bounds.X, sourceY: Screen.PrimaryScreen.Bounds.Y, destinationX: 0, destinationY: 0, blockRegionSize: bitmap.Size, copyPixelOperation: CopyPixelOperation.SourceCopy); var bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); try { return BitmapSource.Create( bitmapData.Width, bitmapData.Height, bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Bgra32, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); } finally { bitmap.UnlockBits(bitmapData); } } } } }
// 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.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; using System.Windows.Media.Imaging; using PixelFormats = System.Windows.Media.PixelFormats; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { internal static class ScreenshotService { private static readonly object s_gate = new object(); /// <summary> /// Takes a picture of the screen and saves it to the location specified by /// <paramref name="fullPath"/>. Files are always saved in PNG format, regardless of the /// file extension. /// </summary> public static void TakeScreenshot(string fullPath) { // This gate prevents concurrency for two reasons: // // 1. Only one screenshot is held in memory at a time to prevent running out of memory for large displays // 2. Only one screenshot is written to disk at a time to avoid exceptions if concurrent calls are writing // to the same file lock (s_gate) { var bitmap = TryCaptureFullScreen(); if (bitmap == null) { return; } var directory = Path.GetDirectoryName(fullPath); Directory.CreateDirectory(directory); using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); encoder.Save(fileStream); } } } /// <summary> /// Captures the full screen to a <see cref="Bitmap"/>. /// </summary> /// <returns> /// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen /// capture can't be created. /// </returns> private static BitmapSource? TryCaptureFullScreen() { var width = Screen.PrimaryScreen.Bounds.Width; var height = Screen.PrimaryScreen.Bounds.Height; if (width <= 0 || height <= 0) { // Don't try to take a screenshot if there is no screen. // This may not be an interactive session. return null; } using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb)) using (var graphics = Graphics.FromImage(bitmap)) { graphics.CopyFromScreen( sourceX: Screen.PrimaryScreen.Bounds.X, sourceY: Screen.PrimaryScreen.Bounds.Y, destinationX: 0, destinationY: 0, blockRegionSize: bitmap.Size, copyPixelOperation: CopyPixelOperation.SourceCopy); var bitmapData = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); try { return BitmapSource.Create( bitmapData.Width, bitmapData.Height, bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Bgra32, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); } finally { bitmap.UnlockBits(bitmapData); } } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/ChangeSignature/AbstractChangeSignatureService.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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { internal abstract class AbstractChangeSignatureService : ILanguageService { protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting"); /// <summary> /// Determines the symbol on which we are invoking ReorderParameters /// </summary> public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken); /// <summary> /// Given a SyntaxNode for which we want to reorder parameters/arguments, find the /// SyntaxNode of a kind where we know how to reorder parameters/arguments. /// </summary> public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node); public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync( IMethodSymbol symbol, Document document, CancellationToken cancellationToken); public abstract Task<SyntaxNode> ChangeSignatureAsync( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode; protected abstract SyntaxToken CommaTokenWithElasticSpace(); /// <summary> /// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3) /// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 }); /// </summary> protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol); protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name); /// <summary> /// Only some languages support: /// - Optional parameters and params arrays simultaneously in declarations /// - Passing the params array as a named argument /// </summary> protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously(); protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor); /// <summary> /// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed. /// </summary> protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol); protected abstract SyntaxGenerator Generator { get; } protected abstract ISyntaxFacts SyntaxFacts { get; } public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false); return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext ? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext)) : ImmutableArray<ChangeSignatureCodeAction>.Empty; } internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var (symbol, selectedIndex) = await GetInvocationSymbolAsync( document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false); // Cross-language symbols will show as metadata, so map it to source if possible. symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol; if (symbol == null) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind); } if (symbol is IMethodSymbol method) { var containingType = method.ContainingType; if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName && containingType != null && containingType.IsDelegateType() && containingType.DelegateInvokeMethod != null) { symbol = containingType.DelegateInvokeMethod; } } if (symbol is IEventSymbol ev) { symbol = ev.Type; } if (symbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null) { symbol = typeSymbol.DelegateInvokeMethod; } else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor)) { symbol = primaryConstructor; } } if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property)) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind); } if (symbol.Locations.Any(loc => loc.IsInMetadata)) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata); } // This should be called after the metadata check above to avoid looking for nodes in metadata. var declarationLocation = symbol.Locations.FirstOrDefault(); if (declarationLocation == null) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata); } var solution = document.Project.Solution; var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!); var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>(); int positionForTypeBinding; var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(); if (reference != null) { var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); positionForTypeBinding = syntax.SpanStart; } else { // There may be no declaring syntax reference, for example delegate Invoke methods. // The user may need to fully-qualify type names, including the type(s) defined in // this document. positionForTypeBinding = 0; } var parameterConfiguration = ParameterConfiguration.Create( GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(), symbol.IsExtensionMethod(), selectedIndex); return new ChangeSignatureAnalysisSucceededContext( declarationDocument, positionForTypeBinding, symbol, parameterConfiguration); } internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken) { return context switch { ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false), CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason), _ => throw ExceptionUtilities.Unreachable, }; async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken) { if (options == null) { return new ChangeSignatureResult(succeeded: false); } var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false); return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage); } } /// <returns>Returns <c>null</c> if the operation is cancelled.</returns> internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context) { if (context is not ChangeSignatureAnalysisSucceededContext succeededContext) { return null; } var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>(); return changeSignatureOptionsService.GetChangeSignatureOptions( succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration); } private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken)) { var streamingProgress = new StreamingProgressCollector(); var engine = new FindReferencesSearchEngine( solution, documents: null, ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod), streamingProgress, FindReferencesSearchOptions.Default); await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false); return streamingProgress.GetReferencedSymbols(); } } #nullable enable private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync( ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken) { var telemetryTimer = Stopwatch.StartNew(); var currentSolution = context.Solution; var declaredSymbol = context.Symbol; var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>(); var definitionToUse = new Dictionary<SyntaxNode, ISymbol>(); string? confirmationMessage = null; var symbols = await FindChangeSignatureReferencesAsync( declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false); var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length; var telemetryNumberOfDeclarationsToUpdate = 0; var telemetryNumberOfReferencesToUpdate = 0; foreach (var symbol in symbols) { var methodSymbol = symbol.Definition as IMethodSymbol; if (methodSymbol != null && (methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet)) { continue; } if (symbol.Definition.Kind == SymbolKind.NamedType) { continue; } if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata)) { confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue; continue; } var symbolWithSyntacticParameters = symbol.Definition; var symbolWithSemanticParameters = symbol.Definition; var includeDefinitionLocations = true; if (symbol.Definition.Kind == SymbolKind.Field) { includeDefinitionLocations = false; } if (symbolWithSyntacticParameters is IEventSymbol eventSymbol) { if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null) { symbolWithSemanticParameters = type.DelegateInvokeMethod; } else { continue; } } if (methodSymbol != null) { if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) { symbolWithSyntacticParameters = methodSymbol.ContainingType; } if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName && methodSymbol.ContainingType != null && methodSymbol.ContainingType.IsDelegateType()) { includeDefinitionLocations = false; } // We update delegates which may have different signature. // It seems it is enough for now to compare delegates by parameter count only. if (methodSymbol.Parameters.Length != declaredSymbolParametersCount) { includeDefinitionLocations = false; } } // Find and annotate all the relevant definitions if (includeDefinitionLocations) { foreach (var def in symbolWithSyntacticParameters.Locations) { if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId)) { continue; } if (!nodesToUpdate.ContainsKey(documentId)) { nodesToUpdate.Add(documentId, new List<SyntaxNode>()); } telemetryNumberOfDeclarationsToUpdate++; AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters); } } // Find and annotate all the relevant references foreach (var location in symbol.Locations) { if (location.Location.IsInMetadata) { confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue; continue; } if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2)) { continue; } if (!nodesToUpdate.ContainsKey(documentId2)) { nodesToUpdate.Add(documentId2, new List<SyntaxNode>()); } telemetryNumberOfReferencesToUpdate++; AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters); } } // Construct all the relevant syntax trees from the base solution var updatedRoots = new Dictionary<DocumentId, SyntaxNode>(); foreach (var docId in nodesToUpdate.Keys) { var doc = currentSolution.GetRequiredDocument(docId); var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>(); var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var nodes = nodesToUpdate[docId]; var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) => { return updater.ChangeSignatureAsync( doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); }); var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation); var formattedRoot = Formatter.Format( newRoot, changeSignatureFormattingAnnotation, doc.Project.Solution.Workspace, options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false), rules: GetFormattingRules(doc), cancellationToken: CancellationToken.None); updatedRoots[docId] = formattedRoot; } // Update the documents using the updated syntax trees foreach (var docId in nodesToUpdate.Keys) { var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]); var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false); var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!); } telemetryTimer.Stop(); ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds); return (currentSolution, confirmationMessage); } #nullable disable private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters) { nodesToUpdate[documentId].Add(nodeToUpdate); if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters) { Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters."); } definitionToUse[nodeToUpdate] = symbolWithSemanticParameters; } private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId) { var tree = location.SourceTree; documentId = solution.GetDocumentId(tree); var document = solution.GetDocument(documentId); var root = tree.GetRoot(); var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true); var updater = document.GetLanguageService<AbstractChangeSignatureService>(); nodeToUpdate = updater.FindNodeToUpdate(document, node); return nodeToUpdate != null; } protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments( ISymbol declarationSymbol, ImmutableArray<IUnifiedArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { // 1. Determine which parameters are permutable var declarationParameters = GetParameters(declarationSymbol); var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod); var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList(); // 2. Create an argument to parameter map, and a parameter to index map for the sort. var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>(); var parameterToIndexMap = new Dictionary<IParameterSymbol, int>(); for (var i = 0; i < declarationParametersToPermute.Length; i++) { var decl = declarationParametersToPermute[i]; var arg = argumentsToPermute[i]; argumentToParameterMap[arg] = decl; var originalIndex = declarationParameters.IndexOf(decl); var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex); // If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke). parameterToIndexMap[decl] = updatedIndex ?? -1; } // 3. Sort the arguments that need to be reordered argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); }); // 4. Add names to arguments where necessary. var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance(); var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0); var seenNamedArgument = false; // Holds the params array argument so it can be // added at the end. IUnifiedArgumentSyntax paramsArrayArgument = null; foreach (var argument in argumentsToPermute) { var param = argumentToParameterMap[argument]; var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param)); if (!actualIndex.HasValue) { continue; } if (!param.IsParams) { // If seen a named argument before, add names for subsequent ones. if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed) { newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation)); seenNamedArgument = true; } else { newArguments.Add(argument); } } else { paramsArrayArgument = argument; } seenNamedArgument |= argument.IsNamed; expectedIndex++; } // 5. Add the params argument with the first value: if (paramsArrayArgument != null) { var param = argumentToParameterMap[paramsArrayArgument]; if (seenNamedArgument && !paramsArrayArgument.IsNamed) { newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation)); seenNamedArgument = true; } else { newArguments.Add(paramsArrayArgument); } } // 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed. var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null; for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++) { if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length) { break; } if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName())) { newArguments.Add(arguments[i]); } } return newArguments.ToImmutableAndFree(); } /// <summary> /// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as /// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters /// to the base <see cref="SignatureChange"/>. /// </summary> private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature) { var realParameters = GetParameters(declarationSymbol); if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length) { var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length); var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p))); var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p))); updatedSignature = new SignatureChange( ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0), ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0)); } return updatedSignature; } private static ImmutableArray<IParameterSymbol> GetParametersToPermute( ImmutableArray<IUnifiedArgumentSyntax> arguments, ImmutableArray<IParameterSymbol> originalParameters, bool isReducedExtensionMethod) { var position = -1 + (isReducedExtensionMethod ? 1 : 0); var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance(); foreach (var argument in arguments) { if (argument.IsNamed) { var name = argument.GetName(); // TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>); var match = originalParameters.FirstOrDefault(p => p.Name == name); if (match == null || originalParameters.IndexOf(match) <= position) { break; } else { position = originalParameters.IndexOf(match); parametersToPermute.Add(match); } } else { position++; if (position >= originalParameters.Length) { break; } parametersToPermute.Add(originalParameters[position]); } } return parametersToPermute.ToImmutableAndFree(); } /// <summary> /// Given the cursor position, find which parameter is selected. /// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for /// the `this` parameter in extension methods (the selected index won't remain 0). /// </summary> protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position) where TNode : SyntaxNode { if (parameters.Count == 0) { return 0; } if (position < parameters.Span.Start) { return 0; } if (position > parameters.Span.End) { return 0; } for (var i = 0; i < parameters.Count - 1; i++) { // `$$,` points to the argument before the separator // but `,$$` points to the argument following the separator if (position <= parameters.GetSeparator(i).Span.Start) { return i; } } return parameters.Count - 1; } protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>( SeparatedSyntaxList<T> list, SignatureChange updatedSignature, Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var numAddedParameters = 0; // Iterate through the list of new parameters and combine any // preexisting parameters with added parameters to construct // the full updated list. var newParameters = ImmutableArray.CreateBuilder<T>(); for (var index = 0; index < reorderedParameters.Length; index++) { var newParam = reorderedParameters[index]; if (newParam is ExistingParameter existingParameter) { var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol)); var param = list[pos]; if (index < list.Count) { param = TransferLeadingWhitespaceTrivia(param, list[index]); } else { param = param.WithLeadingTrivia(); } newParameters.Add(param); } else { // Added parameter var newParameter = createNewParameterMethod((AddedParameter)newParam); if (index < list.Count) { newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]); } else { newParameter = newParameter.WithLeadingTrivia(); } newParameters.Add(newParameter); numAddedParameters++; } } // (a,b,c) // Adding X parameters, need to add X separators. var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length; if (originalParameters.Length == 0) { // () // Adding X parameters, need to add X-1 separators. numSeparatorsToSkip++; } return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip)); } protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode { var separators = ImmutableArray.CreateBuilder<SyntaxToken>(); for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(i < arguments.SeparatorCount ? arguments.GetSeparator(i) : CommaTokenWithElasticSpace()); } return separators.ToImmutable(); } protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync( ISymbol declarationSymbol, SeparatedSyntaxList<SyntaxNode> newArguments, SignatureChange signaturePermutation, bool isReducedExtensionMethod, bool isParamsArrayExpanded, bool generateAttributeArguments, Document document, int position, CancellationToken cancellationToken) { var fullList = ArrayBuilder<SyntaxNode>.GetInstance(); var separators = ArrayBuilder<SyntaxToken>.GetInstance(); var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters(); var indexInListOfPreexistingArguments = 0; var seenNamedArguments = false; var seenOmitted = false; var paramsHandled = false; for (var i = 0; i < updatedParameters.Length; i++) { // Skip this parameter in list of arguments for extension method calls but not for reduced ones. if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter || !isReducedExtensionMethod) { var parameters = GetParameters(declarationSymbol); if (updatedParameters[i] is AddedParameter addedParameter) { // Omitting an argument only works in some languages, depending on whether // there is a params array. We sometimes need to reinterpret an requested // omitted parameter as one with a TODO requested. var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted && parameters.LastOrDefault()?.IsParams == true && !SupportsOptionalAndParamsArrayParametersSimultaneously(); var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray; var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray; if (isCallsiteActuallyOmitted) { seenOmitted = true; seenNamedArguments = true; continue; } var expression = await GenerateInferredCallsiteExpressionAsync( document, position, addedParameter, cancellationToken).ConfigureAwait(false); if (expression == null) { // If we tried to infer the expression but failed, use a TODO instead. isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred; expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue); } // TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator. // https://github.com/dotnet/roslyn/issues/43354 var argument = generateAttributeArguments ? Generator.AttributeArgument( name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null, expression: expression) : Generator.Argument( name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null, refKind: RefKind.None, expression: expression); fullList.Add(argument); separators.Add(CommaTokenWithElasticSpace()); } else { if (indexInListOfPreexistingArguments == parameters.Length - 1 && parameters[indexInListOfPreexistingArguments].IsParams) { // Handling params array if (seenOmitted) { // Need to ensure the params array is an actual array, and that the argument is named. if (isParamsArrayExpanded) { var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]); newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); fullList.Add(newArgument); } else if (indexInListOfPreexistingArguments < newArguments.Count) { var newArgument = newArguments[indexInListOfPreexistingArguments]; newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); fullList.Add(newArgument); } paramsHandled = true; } else { // Normal case. Handled later. } } else if (indexInListOfPreexistingArguments < newArguments.Count) { if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments])) { seenNamedArguments = true; } if (indexInListOfPreexistingArguments < newArguments.SeparatorCount) { separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments)); } var newArgument = newArguments[indexInListOfPreexistingArguments]; if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument)) { newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); } fullList.Add(newArgument); indexInListOfPreexistingArguments++; } } } } if (!paramsHandled) { // Add the rest of existing parameters, e.g. from the params argument. while (indexInListOfPreexistingArguments < newArguments.Count) { if (indexInListOfPreexistingArguments < newArguments.SeparatorCount) { separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments)); } fullList.Add(newArguments[indexInListOfPreexistingArguments++]); } } if (fullList.Count == separators.Count && separators.Count != 0) { separators.Remove(separators.Last()); } return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree()); } private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync( Document document, int position, AddedParameter addedParameter, CancellationToken cancellationToken) { if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var recommender = document.GetRequiredLanguageService<IRecommendationService>(); var recommendations = recommender.GetRecommendedSymbolsAtPosition(document, semanticModel, position, document.Project.Solution.Options, cancellationToken).NamedSymbols; var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource()); // For locals, prefer the one with the closest declaration. Because we used the Recommender, // we do not have to worry about filtering out inaccessible locals. // TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689 var orderedLocalAndParameterSymbols = sourceSymbols .Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter)) .OrderByDescending(s => s.Locations.First().SourceSpan.Start); // No particular ordering preference for properties/fields. var orderedPropertiesAndFields = sourceSymbols .Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field)); var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields); foreach (var symbol in fullyOrderedSymbols) { var symbolType = symbol.GetSymbolType(); if (symbolType == null) { continue; } if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit) { return Generator.IdentifierName(symbol.Name); } } return null; } protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes) { var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>(); var index = 0; SyntaxTrivia lastWhiteSpaceTrivia = default; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { if (syntaxFacts.IsWhitespaceTrivia(trivia)) { lastWhiteSpaceTrivia = trivia; } updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure(); if (!syntaxFacts.IsDocumentationComment(structuredTrivia)) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance(); var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia); for (var i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!syntaxFacts.IsParameterNameXmlElementSyntax(content)) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Length) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree()); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = Generator.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance(); while (index < permutedParamNodes.Length) { extraNodeList.Add(permutedParamNodes[index]); index++; } if (extraNodeList.Any()) { var extraDocComments = Generator.DocumentationCommentTrivia( extraNodeList, node.GetTrailingTrivia(), lastWhiteSpaceTrivia, document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language)); var newTrivia = Generator.Trivia(extraDocComments); updatedLeadingTrivia.Add(newTrivia); } extraNodeList.Free(); return updatedLeadingTrivia.ToImmutable(); } protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken) { if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true) { if (argumentCount > methodSymbol.Parameters.Length) { return true; } if (argumentCount == methodSymbol.Parameters.Length) { if (lastArgumentIsNamed) { // If the last argument is named, then it cannot be part of an expanded params array. return false; } else { var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken); var toType = methodSymbol.Parameters.Last().Type; return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType); } } } 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { internal abstract class AbstractChangeSignatureService : ILanguageService { protected SyntaxAnnotation changeSignatureFormattingAnnotation = new("ChangeSignatureFormatting"); /// <summary> /// Determines the symbol on which we are invoking ReorderParameters /// </summary> public abstract Task<(ISymbol? symbol, int selectedIndex)> GetInvocationSymbolAsync(Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken); /// <summary> /// Given a SyntaxNode for which we want to reorder parameters/arguments, find the /// SyntaxNode of a kind where we know how to reorder parameters/arguments. /// </summary> public abstract SyntaxNode? FindNodeToUpdate(Document document, SyntaxNode node); public abstract Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsFromDelegateInvokeAsync( IMethodSymbol symbol, Document document, CancellationToken cancellationToken); public abstract Task<SyntaxNode> ChangeSignatureAsync( Document document, ISymbol declarationSymbol, SyntaxNode potentiallyUpdatedNode, SyntaxNode originalNode, SignatureChange signaturePermutation, CancellationToken cancellationToken); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract T TransferLeadingWhitespaceTrivia<T>(T newArgument, SyntaxNode oldArgument) where T : SyntaxNode; protected abstract SyntaxToken CommaTokenWithElasticSpace(); /// <summary> /// For some Foo(int x, params int[] p), this helps convert the "1, 2, 3" in Foo(0, 1, 2, 3) /// to "new int[] { 1, 2, 3 }" in Foo(0, new int[] { 1, 2, 3 }); /// </summary> protected abstract SyntaxNode CreateExplicitParamsArrayFromIndividualArguments(SeparatedSyntaxList<SyntaxNode> newArguments, int startingIndex, IParameterSymbol parameterSymbol); protected abstract SyntaxNode AddNameToArgument(SyntaxNode argument, string name); /// <summary> /// Only some languages support: /// - Optional parameters and params arrays simultaneously in declarations /// - Passing the params array as a named argument /// </summary> protected abstract bool SupportsOptionalAndParamsArrayParametersSimultaneously(); protected abstract bool TryGetRecordPrimaryConstructor(INamedTypeSymbol typeSymbol, [NotNullWhen(true)] out IMethodSymbol? primaryConstructor); /// <summary> /// A temporarily hack that should be removed once/if https://github.com/dotnet/roslyn/issues/53092 is fixed. /// </summary> protected abstract ImmutableArray<IParameterSymbol> GetParameters(ISymbol declarationSymbol); protected abstract SyntaxGenerator Generator { get; } protected abstract ISyntaxFacts SyntaxFacts { get; } public async Task<ImmutableArray<ChangeSignatureCodeAction>> GetChangeSignatureCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var context = await GetChangeSignatureContextAsync(document, span.Start, restrictToDeclarations: true, cancellationToken: cancellationToken).ConfigureAwait(false); return context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext ? ImmutableArray.Create(new ChangeSignatureCodeAction(this, changeSignatureAnalyzedSucceedContext)) : ImmutableArray<ChangeSignatureCodeAction>.Empty; } internal async Task<ChangeSignatureAnalyzedContext> GetChangeSignatureContextAsync( Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken) { var (symbol, selectedIndex) = await GetInvocationSymbolAsync( document, position, restrictToDeclarations, cancellationToken).ConfigureAwait(false); // Cross-language symbols will show as metadata, so map it to source if possible. symbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, cancellationToken).ConfigureAwait(false) ?? symbol; if (symbol == null) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind); } if (symbol is IMethodSymbol method) { var containingType = method.ContainingType; if (method.Name == WellKnownMemberNames.DelegateBeginInvokeName && containingType != null && containingType.IsDelegateType() && containingType.DelegateInvokeMethod != null) { symbol = containingType.DelegateInvokeMethod; } } if (symbol is IEventSymbol ev) { symbol = ev.Type; } if (symbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.IsDelegateType() && typeSymbol.DelegateInvokeMethod != null) { symbol = typeSymbol.DelegateInvokeMethod; } else if (TryGetRecordPrimaryConstructor(typeSymbol, out var primaryConstructor)) { symbol = primaryConstructor; } } if (!symbol.MatchesKind(SymbolKind.Method, SymbolKind.Property)) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.IncorrectKind); } if (symbol.Locations.Any(loc => loc.IsInMetadata)) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata); } // This should be called after the metadata check above to avoid looking for nodes in metadata. var declarationLocation = symbol.Locations.FirstOrDefault(); if (declarationLocation == null) { return new CannotChangeSignatureAnalyzedContext(ChangeSignatureFailureKind.DefinedInMetadata); } var solution = document.Project.Solution; var declarationDocument = solution.GetRequiredDocument(declarationLocation.SourceTree!); var declarationChangeSignatureService = declarationDocument.GetRequiredLanguageService<AbstractChangeSignatureService>(); int positionForTypeBinding; var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(); if (reference != null) { var syntax = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); positionForTypeBinding = syntax.SpanStart; } else { // There may be no declaring syntax reference, for example delegate Invoke methods. // The user may need to fully-qualify type names, including the type(s) defined in // this document. positionForTypeBinding = 0; } var parameterConfiguration = ParameterConfiguration.Create( GetParameters(symbol).Select(p => new ExistingParameter(p)).ToImmutableArray<Parameter>(), symbol.IsExtensionMethod(), selectedIndex); return new ChangeSignatureAnalysisSucceededContext( declarationDocument, positionForTypeBinding, symbol, parameterConfiguration); } internal async Task<ChangeSignatureResult> ChangeSignatureWithContextAsync(ChangeSignatureAnalyzedContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken) { return context switch { ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext => await GetChangeSignatureResultAsync(changeSignatureAnalyzedSucceedContext, options, cancellationToken).ConfigureAwait(false), CannotChangeSignatureAnalyzedContext cannotChangeSignatureAnalyzedContext => new ChangeSignatureResult(succeeded: false, changeSignatureFailureKind: cannotChangeSignatureAnalyzedContext.CannotChangeSignatureReason), _ => throw ExceptionUtilities.Unreachable, }; async Task<ChangeSignatureResult> GetChangeSignatureResultAsync(ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult? options, CancellationToken cancellationToken) { if (options == null) { return new ChangeSignatureResult(succeeded: false); } var (updatedSolution, confirmationMessage) = await CreateUpdatedSolutionAsync(context, options, cancellationToken).ConfigureAwait(false); return new ChangeSignatureResult(updatedSolution != null, updatedSolution, context.Symbol.ToDisplayString(), context.Symbol.GetGlyph(), options.PreviewChanges, confirmationMessage: confirmationMessage); } } /// <returns>Returns <c>null</c> if the operation is cancelled.</returns> internal static ChangeSignatureOptionsResult? GetChangeSignatureOptions(ChangeSignatureAnalyzedContext context) { if (context is not ChangeSignatureAnalysisSucceededContext succeededContext) { return null; } var changeSignatureOptionsService = succeededContext.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>(); return changeSignatureOptionsService.GetChangeSignatureOptions( succeededContext.Document, succeededContext.PositionForTypeBinding, succeededContext.Symbol, succeededContext.ParameterConfiguration); } private static async Task<ImmutableArray<ReferencedSymbol>> FindChangeSignatureReferencesAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference_ChangeSignature, cancellationToken)) { var streamingProgress = new StreamingProgressCollector(); var engine = new FindReferencesSearchEngine( solution, documents: null, ReferenceFinders.DefaultReferenceFinders.Add(DelegateInvokeMethodReferenceFinder.DelegateInvokeMethod), streamingProgress, FindReferencesSearchOptions.Default); await engine.FindReferencesAsync(symbol, cancellationToken).ConfigureAwait(false); return streamingProgress.GetReferencedSymbols(); } } #nullable enable private async Task<(Solution updatedSolution, string? confirmationMessage)> CreateUpdatedSolutionAsync( ChangeSignatureAnalysisSucceededContext context, ChangeSignatureOptionsResult options, CancellationToken cancellationToken) { var telemetryTimer = Stopwatch.StartNew(); var currentSolution = context.Solution; var declaredSymbol = context.Symbol; var nodesToUpdate = new Dictionary<DocumentId, List<SyntaxNode>>(); var definitionToUse = new Dictionary<SyntaxNode, ISymbol>(); string? confirmationMessage = null; var symbols = await FindChangeSignatureReferencesAsync( declaredSymbol, context.Solution, cancellationToken).ConfigureAwait(false); var declaredSymbolParametersCount = GetParameters(declaredSymbol).Length; var telemetryNumberOfDeclarationsToUpdate = 0; var telemetryNumberOfReferencesToUpdate = 0; foreach (var symbol in symbols) { var methodSymbol = symbol.Definition as IMethodSymbol; if (methodSymbol != null && (methodSymbol.MethodKind == MethodKind.PropertyGet || methodSymbol.MethodKind == MethodKind.PropertySet)) { continue; } if (symbol.Definition.Kind == SymbolKind.NamedType) { continue; } if (symbol.Definition.Locations.Any(loc => loc.IsInMetadata)) { confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue; continue; } var symbolWithSyntacticParameters = symbol.Definition; var symbolWithSemanticParameters = symbol.Definition; var includeDefinitionLocations = true; if (symbol.Definition.Kind == SymbolKind.Field) { includeDefinitionLocations = false; } if (symbolWithSyntacticParameters is IEventSymbol eventSymbol) { if (eventSymbol.Type is INamedTypeSymbol type && type.DelegateInvokeMethod != null) { symbolWithSemanticParameters = type.DelegateInvokeMethod; } else { continue; } } if (methodSymbol != null) { if (methodSymbol.MethodKind == MethodKind.DelegateInvoke) { symbolWithSyntacticParameters = methodSymbol.ContainingType; } if (methodSymbol.Name == WellKnownMemberNames.DelegateBeginInvokeName && methodSymbol.ContainingType != null && methodSymbol.ContainingType.IsDelegateType()) { includeDefinitionLocations = false; } // We update delegates which may have different signature. // It seems it is enough for now to compare delegates by parameter count only. if (methodSymbol.Parameters.Length != declaredSymbolParametersCount) { includeDefinitionLocations = false; } } // Find and annotate all the relevant definitions if (includeDefinitionLocations) { foreach (var def in symbolWithSyntacticParameters.Locations) { if (!TryGetNodeWithEditableSignatureOrAttributes(def, currentSolution, out var nodeToUpdate, out var documentId)) { continue; } if (!nodesToUpdate.ContainsKey(documentId)) { nodesToUpdate.Add(documentId, new List<SyntaxNode>()); } telemetryNumberOfDeclarationsToUpdate++; AddUpdatableNodeToDictionaries(nodesToUpdate, documentId, nodeToUpdate, definitionToUse, symbolWithSemanticParameters); } } // Find and annotate all the relevant references foreach (var location in symbol.Locations) { if (location.Location.IsInMetadata) { confirmationMessage = FeaturesResources.This_symbol_has_related_definitions_or_references_in_metadata_Changing_its_signature_may_result_in_build_errors_Do_you_want_to_continue; continue; } if (!TryGetNodeWithEditableSignatureOrAttributes(location.Location, currentSolution, out var nodeToUpdate2, out var documentId2)) { continue; } if (!nodesToUpdate.ContainsKey(documentId2)) { nodesToUpdate.Add(documentId2, new List<SyntaxNode>()); } telemetryNumberOfReferencesToUpdate++; AddUpdatableNodeToDictionaries(nodesToUpdate, documentId2, nodeToUpdate2, definitionToUse, symbolWithSemanticParameters); } } // Construct all the relevant syntax trees from the base solution var updatedRoots = new Dictionary<DocumentId, SyntaxNode>(); foreach (var docId in nodesToUpdate.Keys) { var doc = currentSolution.GetRequiredDocument(docId); var updater = doc.Project.LanguageServices.GetRequiredService<AbstractChangeSignatureService>(); var root = await doc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var nodes = nodesToUpdate[docId]; var newRoot = root.ReplaceNodes(nodes, (originalNode, potentiallyUpdatedNode) => { return updater.ChangeSignatureAsync( doc, definitionToUse[originalNode], potentiallyUpdatedNode, originalNode, UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(definitionToUse[originalNode], options.UpdatedSignature), cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); }); var annotatedNodes = newRoot.GetAnnotatedNodes<SyntaxNode>(syntaxAnnotation: changeSignatureFormattingAnnotation); var formattedRoot = Formatter.Format( newRoot, changeSignatureFormattingAnnotation, doc.Project.Solution.Workspace, options: await doc.GetOptionsAsync(cancellationToken).ConfigureAwait(false), rules: GetFormattingRules(doc), cancellationToken: CancellationToken.None); updatedRoots[docId] = formattedRoot; } // Update the documents using the updated syntax trees foreach (var docId in nodesToUpdate.Keys) { var updatedDoc = currentSolution.GetRequiredDocument(docId).WithSyntaxRoot(updatedRoots[docId]); var docWithImports = await ImportAdder.AddImportsFromSymbolAnnotationAsync(updatedDoc, cancellationToken: cancellationToken).ConfigureAwait(false); var reducedDoc = await Simplifier.ReduceAsync(docWithImports, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync(reducedDoc, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false); currentSolution = currentSolution.WithDocumentSyntaxRoot(docId, (await formattedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false))!); } telemetryTimer.Stop(); ChangeSignatureLogger.LogCommitInformation(telemetryNumberOfDeclarationsToUpdate, telemetryNumberOfReferencesToUpdate, (int)telemetryTimer.ElapsedMilliseconds); return (currentSolution, confirmationMessage); } #nullable disable private static void AddUpdatableNodeToDictionaries(Dictionary<DocumentId, List<SyntaxNode>> nodesToUpdate, DocumentId documentId, SyntaxNode nodeToUpdate, Dictionary<SyntaxNode, ISymbol> definitionToUse, ISymbol symbolWithSemanticParameters) { nodesToUpdate[documentId].Add(nodeToUpdate); if (definitionToUse.TryGetValue(nodeToUpdate, out var sym) && sym != symbolWithSemanticParameters) { Debug.Assert(false, "Change Signature: Attempted to modify node twice with different semantic parameters."); } definitionToUse[nodeToUpdate] = symbolWithSemanticParameters; } private static bool TryGetNodeWithEditableSignatureOrAttributes(Location location, Solution solution, out SyntaxNode nodeToUpdate, out DocumentId documentId) { var tree = location.SourceTree; documentId = solution.GetDocumentId(tree); var document = solution.GetDocument(documentId); var root = tree.GetRoot(); var node = root.FindNode(location.SourceSpan, findInsideTrivia: true, getInnermostNodeForTie: true); var updater = document.GetLanguageService<AbstractChangeSignatureService>(); nodeToUpdate = updater.FindNodeToUpdate(document, node); return nodeToUpdate != null; } protected ImmutableArray<IUnifiedArgumentSyntax> PermuteArguments( ISymbol declarationSymbol, ImmutableArray<IUnifiedArgumentSyntax> arguments, SignatureChange updatedSignature, bool isReducedExtensionMethod = false) { // 1. Determine which parameters are permutable var declarationParameters = GetParameters(declarationSymbol); var declarationParametersToPermute = GetParametersToPermute(arguments, declarationParameters, isReducedExtensionMethod); var argumentsToPermute = arguments.Take(declarationParametersToPermute.Length).ToList(); // 2. Create an argument to parameter map, and a parameter to index map for the sort. var argumentToParameterMap = new Dictionary<IUnifiedArgumentSyntax, IParameterSymbol>(); var parameterToIndexMap = new Dictionary<IParameterSymbol, int>(); for (var i = 0; i < declarationParametersToPermute.Length; i++) { var decl = declarationParametersToPermute[i]; var arg = argumentsToPermute[i]; argumentToParameterMap[arg] = decl; var originalIndex = declarationParameters.IndexOf(decl); var updatedIndex = updatedSignature.GetUpdatedIndex(originalIndex); // If there's no value, then we may be handling a method with more parameters than the original symbol (like BeginInvoke). parameterToIndexMap[decl] = updatedIndex ?? -1; } // 3. Sort the arguments that need to be reordered argumentsToPermute.Sort((a1, a2) => { return parameterToIndexMap[argumentToParameterMap[a1]].CompareTo(parameterToIndexMap[argumentToParameterMap[a2]]); }); // 4. Add names to arguments where necessary. var newArguments = ArrayBuilder<IUnifiedArgumentSyntax>.GetInstance(); var expectedIndex = 0 + (isReducedExtensionMethod ? 1 : 0); var seenNamedArgument = false; // Holds the params array argument so it can be // added at the end. IUnifiedArgumentSyntax paramsArrayArgument = null; foreach (var argument in argumentsToPermute) { var param = argumentToParameterMap[argument]; var actualIndex = updatedSignature.GetUpdatedIndex(declarationParameters.IndexOf(param)); if (!actualIndex.HasValue) { continue; } if (!param.IsParams) { // If seen a named argument before, add names for subsequent ones. if ((seenNamedArgument || actualIndex != expectedIndex) && !argument.IsNamed) { newArguments.Add(argument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation)); seenNamedArgument = true; } else { newArguments.Add(argument); } } else { paramsArrayArgument = argument; } seenNamedArgument |= argument.IsNamed; expectedIndex++; } // 5. Add the params argument with the first value: if (paramsArrayArgument != null) { var param = argumentToParameterMap[paramsArrayArgument]; if (seenNamedArgument && !paramsArrayArgument.IsNamed) { newArguments.Add(paramsArrayArgument.WithName(param.Name).WithAdditionalAnnotations(Formatter.Annotation)); seenNamedArgument = true; } else { newArguments.Add(paramsArrayArgument); } } // 6. Add the remaining arguments. These will already have names or be params arguments, but may have been removed. var removedParams = updatedSignature.OriginalConfiguration.ParamsParameter != null && updatedSignature.UpdatedConfiguration.ParamsParameter == null; for (var i = declarationParametersToPermute.Length; i < arguments.Length; i++) { if (!arguments[i].IsNamed && removedParams && i >= updatedSignature.UpdatedConfiguration.ToListOfParameters().Length) { break; } if (!arguments[i].IsNamed || updatedSignature.UpdatedConfiguration.ToListOfParameters().Any(p => p.Name == arguments[i].GetName())) { newArguments.Add(arguments[i]); } } return newArguments.ToImmutableAndFree(); } /// <summary> /// Sometimes signature changes can cascade from a declaration with m parameters to one with n > m parameters, such as /// delegate Invoke methods (m) and delegate BeginInvoke methods (n = m + 2). This method adds on those extra parameters /// to the base <see cref="SignatureChange"/>. /// </summary> private SignatureChange UpdateSignatureChangeToIncludeExtraParametersFromTheDeclarationSymbol(ISymbol declarationSymbol, SignatureChange updatedSignature) { var realParameters = GetParameters(declarationSymbol); if (realParameters.Length > updatedSignature.OriginalConfiguration.ToListOfParameters().Length) { var originalConfigurationParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var updatedConfigurationParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var bonusParameters = realParameters.Skip(originalConfigurationParameters.Length); var originalConfigurationParametersWithExtraParameters = originalConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p))); var updatedConfigurationParametersWithExtraParameters = updatedConfigurationParameters.AddRange(bonusParameters.Select(p => new ExistingParameter(p))); updatedSignature = new SignatureChange( ParameterConfiguration.Create(originalConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0), ParameterConfiguration.Create(updatedConfigurationParametersWithExtraParameters, updatedSignature.OriginalConfiguration.ThisParameter != null, selectedIndex: 0)); } return updatedSignature; } private static ImmutableArray<IParameterSymbol> GetParametersToPermute( ImmutableArray<IUnifiedArgumentSyntax> arguments, ImmutableArray<IParameterSymbol> originalParameters, bool isReducedExtensionMethod) { var position = -1 + (isReducedExtensionMethod ? 1 : 0); var parametersToPermute = ArrayBuilder<IParameterSymbol>.GetInstance(); foreach (var argument in arguments) { if (argument.IsNamed) { var name = argument.GetName(); // TODO: file bug for var match = originalParameters.FirstOrDefault(p => p.Name == <ISymbol here>); var match = originalParameters.FirstOrDefault(p => p.Name == name); if (match == null || originalParameters.IndexOf(match) <= position) { break; } else { position = originalParameters.IndexOf(match); parametersToPermute.Add(match); } } else { position++; if (position >= originalParameters.Length) { break; } parametersToPermute.Add(originalParameters[position]); } } return parametersToPermute.ToImmutableAndFree(); } /// <summary> /// Given the cursor position, find which parameter is selected. /// Returns 0 as the default value. Note that the ChangeSignature dialog adjusts the selection for /// the `this` parameter in extension methods (the selected index won't remain 0). /// </summary> protected static int GetParameterIndex<TNode>(SeparatedSyntaxList<TNode> parameters, int position) where TNode : SyntaxNode { if (parameters.Count == 0) { return 0; } if (position < parameters.Span.Start) { return 0; } if (position > parameters.Span.End) { return 0; } for (var i = 0; i < parameters.Count - 1; i++) { // `$$,` points to the argument before the separator // but `,$$` points to the argument following the separator if (position <= parameters.GetSeparator(i).Span.Start) { return i; } } return parameters.Count - 1; } protected (ImmutableArray<T> parameters, ImmutableArray<SyntaxToken> separators) UpdateDeclarationBase<T>( SeparatedSyntaxList<T> list, SignatureChange updatedSignature, Func<AddedParameter, T> createNewParameterMethod) where T : SyntaxNode { var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters(); var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters(); var numAddedParameters = 0; // Iterate through the list of new parameters and combine any // preexisting parameters with added parameters to construct // the full updated list. var newParameters = ImmutableArray.CreateBuilder<T>(); for (var index = 0; index < reorderedParameters.Length; index++) { var newParam = reorderedParameters[index]; if (newParam is ExistingParameter existingParameter) { var pos = originalParameters.IndexOf(p => p is ExistingParameter ep && ep.Symbol.Equals(existingParameter.Symbol)); var param = list[pos]; if (index < list.Count) { param = TransferLeadingWhitespaceTrivia(param, list[index]); } else { param = param.WithLeadingTrivia(); } newParameters.Add(param); } else { // Added parameter var newParameter = createNewParameterMethod((AddedParameter)newParam); if (index < list.Count) { newParameter = TransferLeadingWhitespaceTrivia(newParameter, list[index]); } else { newParameter = newParameter.WithLeadingTrivia(); } newParameters.Add(newParameter); numAddedParameters++; } } // (a,b,c) // Adding X parameters, need to add X separators. var numSeparatorsToSkip = originalParameters.Length - reorderedParameters.Length; if (originalParameters.Length == 0) { // () // Adding X parameters, need to add X-1 separators. numSeparatorsToSkip++; } return (newParameters.ToImmutable(), GetSeparators(list, numSeparatorsToSkip)); } protected ImmutableArray<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip) where T : SyntaxNode { var separators = ImmutableArray.CreateBuilder<SyntaxToken>(); for (var i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++) { separators.Add(i < arguments.SeparatorCount ? arguments.GetSeparator(i) : CommaTokenWithElasticSpace()); } return separators.ToImmutable(); } protected virtual async Task<SeparatedSyntaxList<SyntaxNode>> AddNewArgumentsToListAsync( ISymbol declarationSymbol, SeparatedSyntaxList<SyntaxNode> newArguments, SignatureChange signaturePermutation, bool isReducedExtensionMethod, bool isParamsArrayExpanded, bool generateAttributeArguments, Document document, int position, CancellationToken cancellationToken) { var fullList = ArrayBuilder<SyntaxNode>.GetInstance(); var separators = ArrayBuilder<SyntaxToken>.GetInstance(); var updatedParameters = signaturePermutation.UpdatedConfiguration.ToListOfParameters(); var indexInListOfPreexistingArguments = 0; var seenNamedArguments = false; var seenOmitted = false; var paramsHandled = false; for (var i = 0; i < updatedParameters.Length; i++) { // Skip this parameter in list of arguments for extension method calls but not for reduced ones. if (updatedParameters[i] != signaturePermutation.UpdatedConfiguration.ThisParameter || !isReducedExtensionMethod) { var parameters = GetParameters(declarationSymbol); if (updatedParameters[i] is AddedParameter addedParameter) { // Omitting an argument only works in some languages, depending on whether // there is a params array. We sometimes need to reinterpret an requested // omitted parameter as one with a TODO requested. var forcedCallsiteErrorDueToParamsArray = addedParameter.CallSiteKind == CallSiteKind.Omitted && parameters.LastOrDefault()?.IsParams == true && !SupportsOptionalAndParamsArrayParametersSimultaneously(); var isCallsiteActuallyOmitted = addedParameter.CallSiteKind == CallSiteKind.Omitted && !forcedCallsiteErrorDueToParamsArray; var isCallsiteActuallyTODO = addedParameter.CallSiteKind == CallSiteKind.Todo || forcedCallsiteErrorDueToParamsArray; if (isCallsiteActuallyOmitted) { seenOmitted = true; seenNamedArguments = true; continue; } var expression = await GenerateInferredCallsiteExpressionAsync( document, position, addedParameter, cancellationToken).ConfigureAwait(false); if (expression == null) { // If we tried to infer the expression but failed, use a TODO instead. isCallsiteActuallyTODO |= addedParameter.CallSiteKind == CallSiteKind.Inferred; expression = Generator.ParseExpression(isCallsiteActuallyTODO ? "TODO" : addedParameter.CallSiteValue); } // TODO: Need to be able to specify which kind of attribute argument it is to the SyntaxGenerator. // https://github.com/dotnet/roslyn/issues/43354 var argument = generateAttributeArguments ? Generator.AttributeArgument( name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null, expression: expression) : Generator.Argument( name: seenNamedArguments || addedParameter.CallSiteKind == CallSiteKind.ValueWithName ? addedParameter.Name : null, refKind: RefKind.None, expression: expression); fullList.Add(argument); separators.Add(CommaTokenWithElasticSpace()); } else { if (indexInListOfPreexistingArguments == parameters.Length - 1 && parameters[indexInListOfPreexistingArguments].IsParams) { // Handling params array if (seenOmitted) { // Need to ensure the params array is an actual array, and that the argument is named. if (isParamsArrayExpanded) { var newArgument = CreateExplicitParamsArrayFromIndividualArguments(newArguments, indexInListOfPreexistingArguments, parameters[indexInListOfPreexistingArguments]); newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); fullList.Add(newArgument); } else if (indexInListOfPreexistingArguments < newArguments.Count) { var newArgument = newArguments[indexInListOfPreexistingArguments]; newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); fullList.Add(newArgument); } paramsHandled = true; } else { // Normal case. Handled later. } } else if (indexInListOfPreexistingArguments < newArguments.Count) { if (SyntaxFacts.IsNamedArgument(newArguments[indexInListOfPreexistingArguments])) { seenNamedArguments = true; } if (indexInListOfPreexistingArguments < newArguments.SeparatorCount) { separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments)); } var newArgument = newArguments[indexInListOfPreexistingArguments]; if (seenNamedArguments && !SyntaxFacts.IsNamedArgument(newArgument)) { newArgument = AddNameToArgument(newArgument, parameters[indexInListOfPreexistingArguments].Name); } fullList.Add(newArgument); indexInListOfPreexistingArguments++; } } } } if (!paramsHandled) { // Add the rest of existing parameters, e.g. from the params argument. while (indexInListOfPreexistingArguments < newArguments.Count) { if (indexInListOfPreexistingArguments < newArguments.SeparatorCount) { separators.Add(newArguments.GetSeparator(indexInListOfPreexistingArguments)); } fullList.Add(newArguments[indexInListOfPreexistingArguments++]); } } if (fullList.Count == separators.Count && separators.Count != 0) { separators.Remove(separators.Last()); } return Generator.SeparatedList(fullList.ToImmutableAndFree(), separators.ToImmutableAndFree()); } private async Task<SyntaxNode> GenerateInferredCallsiteExpressionAsync( Document document, int position, AddedParameter addedParameter, CancellationToken cancellationToken) { if (addedParameter.CallSiteKind != CallSiteKind.Inferred || !addedParameter.TypeBinds) { return null; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var recommender = document.GetRequiredLanguageService<IRecommendationService>(); var recommendations = recommender.GetRecommendedSymbolsAtPosition(document, semanticModel, position, document.Project.Solution.Options, cancellationToken).NamedSymbols; var sourceSymbols = recommendations.Where(r => r.IsNonImplicitAndFromSource()); // For locals, prefer the one with the closest declaration. Because we used the Recommender, // we do not have to worry about filtering out inaccessible locals. // TODO: Support range variables here as well: https://github.com/dotnet/roslyn/issues/44689 var orderedLocalAndParameterSymbols = sourceSymbols .Where(s => s.IsKind(SymbolKind.Local) || s.IsKind(SymbolKind.Parameter)) .OrderByDescending(s => s.Locations.First().SourceSpan.Start); // No particular ordering preference for properties/fields. var orderedPropertiesAndFields = sourceSymbols .Where(s => s.IsKind(SymbolKind.Property) || s.IsKind(SymbolKind.Field)); var fullyOrderedSymbols = orderedLocalAndParameterSymbols.Concat(orderedPropertiesAndFields); foreach (var symbol in fullyOrderedSymbols) { var symbolType = symbol.GetSymbolType(); if (symbolType == null) { continue; } if (semanticModel.Compilation.ClassifyCommonConversion(symbolType, addedParameter.Type).IsImplicit) { return Generator.IdentifierName(symbol.Name); } } return null; } protected ImmutableArray<SyntaxTrivia> GetPermutedDocCommentTrivia(Document document, SyntaxNode node, ImmutableArray<SyntaxNode> permutedParamNodes) { var updatedLeadingTrivia = ImmutableArray.CreateBuilder<SyntaxTrivia>(); var index = 0; SyntaxTrivia lastWhiteSpaceTrivia = default; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var trivia in node.GetLeadingTrivia()) { if (!trivia.HasStructure) { if (syntaxFacts.IsWhitespaceTrivia(trivia)) { lastWhiteSpaceTrivia = trivia; } updatedLeadingTrivia.Add(trivia); continue; } var structuredTrivia = trivia.GetStructure(); if (!syntaxFacts.IsDocumentationComment(structuredTrivia)) { updatedLeadingTrivia.Add(trivia); continue; } var updatedNodeList = ArrayBuilder<SyntaxNode>.GetInstance(); var structuredContent = syntaxFacts.GetContentFromDocumentationCommentTriviaSyntax(trivia); for (var i = 0; i < structuredContent.Count; i++) { var content = structuredContent[i]; if (!syntaxFacts.IsParameterNameXmlElementSyntax(content)) { updatedNodeList.Add(content); continue; } // Found a param tag, so insert the next one from the reordered list if (index < permutedParamNodes.Length) { updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia())); index++; } else { // Inspecting a param element that we are deleting but not replacing. } } var newDocComments = Generator.DocumentationCommentTriviaWithUpdatedContent(trivia, updatedNodeList.ToImmutableAndFree()); newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia()); var newTrivia = Generator.Trivia(newDocComments); updatedLeadingTrivia.Add(newTrivia); } var extraNodeList = ArrayBuilder<SyntaxNode>.GetInstance(); while (index < permutedParamNodes.Length) { extraNodeList.Add(permutedParamNodes[index]); index++; } if (extraNodeList.Any()) { var extraDocComments = Generator.DocumentationCommentTrivia( extraNodeList, node.GetTrailingTrivia(), lastWhiteSpaceTrivia, document.Project.Solution.Options.GetOption(FormattingOptions.NewLine, document.Project.Language)); var newTrivia = Generator.Trivia(extraDocComments); updatedLeadingTrivia.Add(newTrivia); } extraNodeList.Free(); return updatedLeadingTrivia.ToImmutable(); } protected static bool IsParamsArrayExpandedHelper(ISymbol symbol, int argumentCount, bool lastArgumentIsNamed, SemanticModel semanticModel, SyntaxNode lastArgumentExpression, CancellationToken cancellationToken) { if (symbol is IMethodSymbol methodSymbol && methodSymbol.Parameters.LastOrDefault()?.IsParams == true) { if (argumentCount > methodSymbol.Parameters.Length) { return true; } if (argumentCount == methodSymbol.Parameters.Length) { if (lastArgumentIsNamed) { // If the last argument is named, then it cannot be part of an expanded params array. return false; } else { var fromType = semanticModel.GetTypeInfo(lastArgumentExpression, cancellationToken); var toType = methodSymbol.Parameters.Last().Type; return !semanticModel.Compilation.HasImplicitConversion(fromType.Type, toType); } } } return false; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/SymbolCompletionProviderTests.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.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders <UseExportProvider> Public Class SymbolCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Private Const s_unicodeEllipsis = ChrW(&H2026) Friend Overrides Function GetCompletionProviderType() As Type Return GetType(SymbolCompletionProvider) End Function #Region "StandaloneNamespaceAndTypeSourceTests" Private Async Function VerifyNSATIsAbsentAsync(markup As String) As Task ' Verify namespace 'System' is absent Await VerifyItemIsAbsentAsync(markup, "System") ' Verify type 'String' is absent Await VerifyItemIsAbsentAsync(markup, "String") End Function Private Async Function VerifyNSATExistsAsync(markup As String) As Task ' Verify namespace 'System' is absent Await VerifyItemExistsAsync(markup, "System") ' Verify type 'String' is absent Await VerifyItemExistsAsync(markup, "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEmptyFile() As Task Await VerifyNSATIsAbsentAsync("$$") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEmptyFileWithImports() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", "$$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As $$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As { II, $$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As $$)")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As { II, $$})")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements $$.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements3() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements I.Method, $$.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As $$ Implements II.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs3() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method(ByVal args As $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAsNew() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d As New $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGetType1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = GetType($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeOfIs() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TypeOf d Is $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = New $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayCreation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d() = New $$() {"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CType(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TryCast(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = DirectCast(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayType() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d() as $$("))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableType() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as $$?"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList1() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", CreateContent("Class A(Of $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList2() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", CreateContent("Class A(Of T, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as D(Of $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as D(Of A, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInferredFieldInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim anonymousCust2 = New With {Key $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedFieldInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim anonymousCust = New With {.Name = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReturnStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Return $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIfStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("If $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIfStatement2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("If Var1 Then", "Else If $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCatchFilterClause() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Try", "Catch ex As Exception when $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestErrorStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Error $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Select $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Select Case $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case 1, $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case $$ To")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case 1 To $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRelationalCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case Is > $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRelationalCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case >= $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSyncLockStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("SyncLock $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileOrUntilClause1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Do While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileOrUntilClause2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Do Until $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = 1 To $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStepClause() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = 1 To 10 Step $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForEachStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For Each I in $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Using $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestThrowStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Throw $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAssignmentStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$ = a"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAssignmentStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("a = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCallStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Call $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCallStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(1)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("AddHandler $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("AddHandler T.Event, AddressOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("RemoveHandler $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("RemoveHandler T.Event, AddressOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWithStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("With $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = ($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeOfIs2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = TypeOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMemberAccessExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$.Name"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMemberAccessExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$!Name"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvocationExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(1)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(Of Integer)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CType($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast5() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TryCast($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast6() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = DirectCast($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuiltInCase() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CInt($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = $$ + d"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = d + $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUnaryExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = +$$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryConditionExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If($$,"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryConditionExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If($$, a, b"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, $$, c"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, b, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSingleArgument() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("D($$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedArgument() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("D(Name := $$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeArgument1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a($$ To 10)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeArgument2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a(0 To $$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionRangeVariable() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From var in $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpressionRangeVariable() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From var In collection Let b = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFunctionAggregation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In col Aggregate o In c.o Into an = Any($$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhereQueryOperator() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In col Where $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionWhileQueryOperator1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim customerList = From c In cust Order By c.C Skip While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionWhileQueryOperator2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim customerList = From c In cust Order By c.C Take While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionQueryOperator1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In cust Skip $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionQueryOperator2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In cust Take $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestJoinCondition1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim p1 = From p In P Join d In Desc On $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestJoinCondition2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim p1 = From p In P Join d In Desc On p.P Equals $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOrdering() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From b In books Order By $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestXmlEmbeddedExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim book As XElement = <book isbn=<%= $$ %>></book>"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNextStatement1() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("For i = 1 To 10", "Next $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNextStatement2() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("For i = 1 To 10", "Next i, $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEraseStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Erase $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEraseStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Erase i, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionInitializer1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = new List(Of Integer) from { $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionInitializer2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = { $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestStringLiteral() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = ""$$"""))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestComment1() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("' $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestComment2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("'", "$$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInactiveRegion1() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("#IF False Then", " $$")))) End Function #Region "Tests that verify namespaces and types separately" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAliasImportsClause1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports T = $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports T = $$"), "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAliasImportsClause2() As Task Await VerifyItemExistsAsync("Imports $$ = S", "System") Await VerifyItemIsAbsentAsync("Imports $$ = S", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersImportsClause1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports $$"), "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersImportsClause2() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports System, $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports System, $$"), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", CreateContent("<$$>")), "System") Await VerifyItemExistsAsync(AddImportsStatement("Imports System", CreateContent("<$$>")), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes2() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("<$$>", "Class Cl")), "System") Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("<$$>", "Class Cl")), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes3() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class Cl", " <$$>", " Function Method()")), "System") Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class Cl", " <$$>", " Function Method()")), "String") End Function #End Region #End Region #Region "SymbolCompletionProviderTests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IsCommitCharacterTest() As Task Const code = " Imports System Class C Sub M() $$ End Sub End Class" Await VerifyCommonCommitCharactersAsync(code, textTypedSoFar:="") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub IsTextualTriggerCharacterTest() TestCommonIsTextualTriggerCharacter() End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SendEnterThroughToEditorTest() As Task Const code = " Imports System Class C Sub M() $$ End Sub End Class" Await VerifySendEnterThroughToEditorAsync(code, "Int32", expected:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterDateLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call #1/1/2010#.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterStringLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call """".$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterTrueLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call True.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterFalseLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call False.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterNumericLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call 2.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterCharacterLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call ""c""c.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersAfterNothingLiteral() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod("Call Nothing.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedDateLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (#1/1/2010#).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedStringLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call ("""").$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedTrueLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (True).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedFalseLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (False).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedNumericLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (2).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedCharacterLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (""c""c).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersAfterParenthesizedNothingLiteral() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (Nothing).$$")), "Equals") End Function <WorkItem(539243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539243")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedClassesInImports() As Task Await VerifyItemExistsAsync("Imports System.$$", "Console") End Function <WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceTypesAvailableInImportsAlias() As Task Await VerifyItemExistsAsync("Imports S = System.$$", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceTypesAvailableInImports() As Task Await VerifyItemExistsAsync("Imports System.$$", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVarInMethod() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Dim banana As Integer = 4" + vbCrLf + "$$")), "banana") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommandCompletionsInScript() As Task Await VerifyItemExistsAsync(<text>#$$</text>.Value, "#R", sourceCodeKind:=SourceCodeKind.Script) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReferenceCompletionsInScript() As Task Await VerifyItemExistsAsync(<text>#r "$$"</text>.Value, "System.dll", sourceCodeKind:=SourceCodeKind.Script) End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "s") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "Method") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "field") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "M") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMe() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Event X() Sub Test() Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMyClass() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Shared Event X() Sub Test() MyClass.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMyBase() As Task Await VerifyItemIsAbsentAsync( <Text> Class C1 Public Event E(x As Integer) End Class Class C2 Inherits C1 Sub M1() MyBase.$$ End Sub End Class </Text>.Value, "E") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterInstanceMember() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Shared Event X() Sub Test() Dim a As New EventClass() a.$$ End Sub End Class </Text>.Value, "E") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterMeInAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() AddHandler Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterInstanceMemberInAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() AddHandler a.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterInstanceMemberInParenthesizedAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() AddHandler (a.$$), a.XEvent End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterMeInRemoveHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() RemoveHandler Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoImplicitlyDeclaredMembersFromEventDeclarationAfterMe() As Task Dim source = <Text> Class EventClass Public Event X() Sub Test() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "XEventHandler") Await VerifyItemIsAbsentAsync(source, "XEvent") Await VerifyItemIsAbsentAsync(source, "add_X") Await VerifyItemIsAbsentAsync(source, "remove_X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoImplicitlyDeclaredMembersFromEventDeclarationAfterInstance() As Task Dim source = <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() a.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "XEventHandler") Await VerifyItemIsAbsentAsync(source, "XEvent") Await VerifyItemIsAbsentAsync(source, "add_X") Await VerifyItemIsAbsentAsync(source, "remove_X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredEventHandler() As Task Dim source = <Text> Class EventClass Public Event X() Dim a As $$ End Class </Text>.Value Await VerifyItemExistsAsync(source, "XEventHandler") End Function <WorkItem(529570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529570")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredFieldFromWithEvents() As Task Dim source = <Text> Public Class C1 Protected WithEvents w As C1 = Me Sub Goo() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "_w") End Function <WorkItem(529147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529147")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredFieldFromAutoProperty() As Task Dim source = <Text> Class C1 Property X As C1 Sub test() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "_X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingBeforeDot() As Task Dim code = <Text> Module Module1 Sub Main() .$$ End Sub End Module </Text>.Value Await VerifyItemIsAbsentAsync(code, "Main") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterWithMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "s") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterWithMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "Method") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterWithMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "field") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterWithMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNestedWithBlocks() As Task Await VerifyItemExistsAsync( <Text> Class C Sub M() Dim s As String = "" With s With .Length .$$ End With End With End Sub End Class </Text>.Value, "ToString") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembers() As Task Await VerifyItemExistsAsync( <Text> $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersAfterStatement() As Task Await VerifyItemExistsAsync( <Text> Dim x = 1: $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) Await VerifyItemExistsAsync( <Text> Dim x = 1 $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) Await VerifyItemIsAbsentAsync( <Text> Dim x = 1 $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalStatementMembersBeforeDirectives() As Task Await VerifyItemIsAbsentAsync( <Text> $$ #If DEBUG #End If </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersInsideDirectives() As Task Await VerifyItemIsAbsentAsync( <Text> #If $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersAfterAnnotation() As Task Await VerifyItemIsAbsentAsync( <Text><![CDATA[ <Annotation> $$ ]]></Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoSharedMembers() As Task Dim test = <Text> Class C Sub M() Dim s = 1 s.$$ End Sub End Class </Text>.Value ' This is an intentional change from Dev12 behavior where constant ' field members were shown Await VerifyItemIsAbsentAsync(test, "MaxValue") Await VerifyItemIsAbsentAsync(test, "ReferenceEquals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelAfterGoto1() As Task Dim test = <Text> Class C Sub M() Goo: Dim i As Integer Goto $$" </Text>.Value Await VerifyItemExistsAsync(test, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelAfterGoto2() As Task Dim test = <Text> Class C Sub M() Goo: Dim i As Integer Goto Goo $$" </Text>.Value Await VerifyItemIsAbsentAsync(test, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LabelAfterGoto3() As Task Dim test = <Text> Class C Sub M() 10: Dim i As Integer Goto $$" </Text>.Value.NormalizeLineEndings() Dim text As String = Nothing Dim position As Integer MarkupTestFile.GetPosition(test, text, position) ' We don't trigger intellisense within numeric literals, so we ' explicitly test only the "nothing typed" case. ' This is also the Dev12 behavior for suggesting labels. Await VerifyAtPositionAsync( text, position, usePreviousCharAsTrigger:=True, expectedItemOrNull:="10", expectedDescriptionOrNull:=Nothing, sourceCodeKind:=SourceCodeKind.Regular, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, matchingFilters:=Nothing) End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias1() As Task Dim test = <Text> Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M N.$$ End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "A") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias2() As Task Dim test = <Text> Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M N.A.$$ End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "M") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias3() As Task Dim test = <Text> Imports System Imports System.Collections.Generic Imports System.Linq Imports N = NS1.NS2 Module Program Sub Main(args As String()) N.$$ End Sub End Module Namespace NS1.NS2 Public Class A Public Shared Sub M End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "A") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias4() As Task Dim test = <Text> Imports System Imports System.Collections.Generic Imports System.Linq Imports N = NS1.NS2 Module Program Sub Main(args As String()) N.A.$$ End Sub End Module Namespace NS1.NS2 Public Class A Public Shared Sub M End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "M") End Function <WorkItem(541399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541399")> <WorkItem(529190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529190")> <WpfFact(Skip:="529190"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterSingleLineIf() As Task Dim test = <Text> Module Program Sub Main(args As String()) Dim x1 As Integer If True Then $$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(test, "x1") End Function <WorkItem(540442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540442")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyInterfacesInImplementsStatements() As Task Dim test = <Text> Interface IOuter Delegate Sub Del() Interface INested Sub DoNested() End Interface End Interface Class nested Implements IOuter.$$ </Text> Await VerifyItemExistsAsync(test.Value, "INested") Await VerifyItemIsAbsentAsync(test.Value, "Del") End Function <WorkItem(540442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540442")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNestedInterfaceInImplementsClause() As Task Dim test = <Text> Interface IOuter Sub DoOuter() Interface INested Sub DoNested() End Interface End Interface Class nested Implements IOuter.INested Sub DoStuff() implements IOuter.$$ </Text> Await VerifyItemExistsAsync(test.Value, "INested") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingAfterBadQualifiedImplementsClause() As Task Dim test = <Text> Class SomeClass Implements Gibberish.$$ End Class </Text> Await VerifyNoItemsExistAsync(test.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingAfterBadImplementsClause() As Task Dim test = <Text> Module Module1 Sub Goo() End Sub End Module Class SomeClass Sub DoStuff() Implements Module1.$$ </Text> Await VerifyItemIsAbsentAsync(test.Value, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescriptionGenericTypeParameter() As Task Dim test = <Text><![CDATA[ Class SomeClass(Of T) Sub M() $$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "T", $"T {FeaturesResources.in_} SomeClass(Of T)") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeName() As Task Dim test = <Text><![CDATA[ Imports System <$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameAfterSpecifier() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeList() As Task Dim test = <Text><![CDATA[ Imports System <CLSCompliant,$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeListAfterSpecifier() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:CLSCompliant,Assembly:$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameBeforeClass() As Task Dim test = <Text><![CDATA[ Imports System <$$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameAfterSpecifierBeforeClass() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:$$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeArgumentList() As Task Dim test = <Text><![CDATA[ Imports System <CLSCompliant($$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliantAttribute") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliant") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInsideClass() As Task Dim test = <Text><![CDATA[ Imports System Public Class C Dim c As $$ End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliantAttribute") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliant") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewAfterMeWhenFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Me.$$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMeWhenNotFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Dim x As Integer Me.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMeWhenFirstStatementInSingleCtor() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewAfterMyClassWhenFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMyClassWhenNotFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Dim x As Integer MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMyClassWhenFirstStatementInSingleCtor() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext1() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim markup = <Text><![CDATA[ Imports System <$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Bar") Await VerifyItemIsAbsentAsync(markup, "D") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext2() As Task Dim markup = <Text><![CDATA[ Imports System <Bar.$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") Await VerifyItemIsAbsentAsync(markup, "C1") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext3() As Task Dim markup = <Text><![CDATA[ Imports System <Bar.Goo.$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Something") Await VerifyItemIsAbsentAsync(markup, "C2") End Function <WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute1() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute2() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.$$> ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Namespace2") Await VerifyItemExistsAsync(markup, "Namespace3") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute3() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.Namespace3.$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace4") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute4() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.Namespace3.Namespace4.$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Custom") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() As Task Dim markup = <Text><![CDATA[ Imports Namespace1Alias = Namespace1 Imports Namespace2Alias = Namespace1.Namespace2 Imports Namespace3Alias = Namespace1.Namespace3 Imports Namespace4Alias = Namespace1.Namespace3.Namespace4 Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace1Alias") Await VerifyItemIsAbsentAsync(markup, "Namespace2Alias") Await VerifyItemExistsAsync(markup, "Namespace3Alias") Await VerifyItemExistsAsync(markup, "Namespace4Alias") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithoutNestedAttribute() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class NonAttribute Inherits System.NonAttribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Namespace1") End Function <WorkItem(542737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542737")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestQueryVariableAfterSelectClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From num In Enumerable.Range(3, 4) Select $$ ]]></Text>.Value Await VerifyItemExistsAsync(markup, "num") End Function <WorkItem(542683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542683")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplementsClassesWithNestedInterfaces() As Task Dim markup = <Text><![CDATA[ Interface MyInterface1 Class MyClass2 Interface MyInterface3 End Interface End Class Class MyClass3 End Class End Interface Class D Implements MyInterface1.$$ End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "MyClass2") Await VerifyItemIsAbsentAsync(markup, "MyClass3") End Function <WorkItem(542683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542683")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplementsClassesWithNestedInterfacesClassOutermost() As Task Dim markup = <Text><![CDATA[ Class MyClass1 Class MyClass2 Interface MyInterface End Interface End Class End Class Class G Implements $$ End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "MyClass1") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select i,$$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select i, $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim arr = New Integer() {1} Dim query = From i In arr Group By i Into $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Count") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into Group, $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto4() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into g = $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Distinct") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Distinct") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = Distinct(), $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Sum") End Function <WorkItem(543137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543137")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAndKeywordInComplexJoin() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main(args As String()) Dim arr = New Byte() {4, 5} Dim q2 = From num In arr Join n1 In arr On num.ToString() Equals n1.ToString() And $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "num") End Function <WorkItem(543181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543181")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterGroupKeywordInGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From i1 In New Integer() {4, 5} Group $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") End Function <WorkItem(543182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543182")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterByInGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From i1 In New Integer() {3, 2} Group i1 By $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") End Function <WorkItem(543210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543210")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterByInsideExprVarDeclGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q1 = From i1 In arr Group i1 By i2 = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") Await VerifyItemExistsAsync(markup, "arr") Await VerifyItemExistsAsync(markup, "args") End Function <WorkItem(543213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterGroupInsideExprVarDeclGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q1 = From i1 In arr Group i1 = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") Await VerifyItemExistsAsync(markup, "arr") Await VerifyItemExistsAsync(markup, "args") End Function <WorkItem(543246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543246")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAggregateKeyword() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim query = Aggregate $$ ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDelegateCreationExpression1() As Task Dim markup = <Text> Module Program Sub Main(args As String()) Dim f1 As New Goo2($$ End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </Text>.Value Await VerifyItemIsAbsentAsync(markup, "Goo2") Await VerifyItemIsAbsentAsync(markup, "Bar2") End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDelegateCreationExpression2() As Task Dim markup = <Text> Module Program Sub Main(args As String()) Dim f1 = New Goo2($$ End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </Text>.Value Await VerifyItemIsAbsentAsync(markup, "Goo2") Await VerifyItemIsAbsentAsync(markup, "Bar2") End Function <WorkItem(619388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619388")> <WpfFact(Skip:="619388"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverloadsHiding() As Task Dim markup = <Text><![CDATA[ Public Class Base Sub Configure() End Sub End Class Public Class Derived Inherits Base Overloads Sub Configure() Config$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Configure", "Sub Derived.Configure()") Await VerifyItemIsAbsentAsync(markup, "Configure", "Sub Base.Configure()") End Function <WorkItem(543580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543580")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterMyBaseDot1() As Task Dim markup = <Text><![CDATA[ Public Class Base Protected Sub Configure() Console.WriteLine("test") End Sub End Class Public Class Inherited Inherits Base Public Shadows Sub Configure() MyBase.$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Configure") End Function <WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingMyBaseDotInScriptContext() As Task Await VerifyItemIsAbsentAsync("MyBase.$$", "ToString", sourceCodeKind:=SourceCodeKind.Script) End Function <WorkItem(543580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543580")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterMyBaseDot2() As Task Dim markup = <Text> Public Class Base Protected Sub Goo() Console.WriteLine("test") End Sub End Class Public Class Inherited Inherits Base Public Sub Bar() MyBase.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "Goo") Await VerifyItemIsAbsentAsync(markup, "Bar") End Function <WorkItem(543547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543547")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterRaiseEvent() As Task Dim markup = <Text> Module Program Public Event NewRegistrations(ByVal pStudents As String) Sub Main(args As String()) RaiseEvent $$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "NewRegistrations") End Function <WorkItem(543730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543730")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInheritedEventsAfterRaiseEvent() As Task Dim markup = <Text> Class C1 Event baseEvent End Class Class C2 Inherits C1 Event derivedEvent(x As Integer) Sub M() RaiseEvent $$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "derivedEvent") Await VerifyItemIsAbsentAsync(markup, "baseEvent") End Function <WorkItem(529116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529116")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInSingleLineLambda1() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x5 = Function(x1) $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "x1") Await VerifyItemExistsAsync(markup, "x5") End Function <WorkItem(529116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529116")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInSingleLineLambda2() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x5 = Function(x1)$$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "x1") Await VerifyItemExistsAsync(markup, "x5") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <WorkItem(530595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530595")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsInSharedMethod() As Task Dim markup = <Text> Class C Private x As Integer Shared Sub M() $$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsInSharedFieldInitializer() As Task Dim markup = <Text> Class C Private x As Integer Private Shared y As Integer = $$ End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsInSharedMethod() As Task Dim markup = <Text> Class C Private Shared x As Integer Shared Sub M() $$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsInSharedFieldInitializer() As Task Dim markup = <Text> Class C Private Shared x As Integer Private Shared y As Integer = $$ End Class </Text>.Value Await VerifyItemExistsAsync(markup, "x") End Function <WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsFromOuterClassInInstanceMethod() As Task Dim markup = <Text> Class outer Dim i As Integer Class inner Sub M() $$ End Sub End Class End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "i") End Function <WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsFromOuterClassInInstanceMethod() As Task Dim markup = <Text> Class outer Shared i As Integer Class inner Sub M() $$ End Sub End Class End Class </Text>.Value Await VerifyItemExistsAsync(markup, "i") End Function <WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyEnumMembersInEnumTypeMemberAccess() As Task Dim markup = <Text> Class C Enum x a b c End Enum Sub M() x.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "a") Await VerifyItemExistsAsync(markup, "b") Await VerifyItemExistsAsync(markup, "c") Await VerifyItemIsAbsentAsync(markup, "Equals") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping1() As Task Dim markup = <Text> Module [Structure] Sub M() dim [dim] = 0 console.writeline($$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "dim") Await VerifyItemIsAbsentAsync(markup, "[dim]") Await VerifyItemExistsAsync(markup, "Structure") Await VerifyItemIsAbsentAsync(markup, "[Structure]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping2() As Task Dim markup = <Text> Module [Structure] Sub [dim]() End Sub Sub [New]() End Sub Sub [rem]() [Structure].$$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "dim") Await VerifyItemIsAbsentAsync(markup, "[dim]") Await VerifyItemExistsAsync(markup, "New") Await VerifyItemIsAbsentAsync(markup, "[New]") Await VerifyItemExistsAsync(markup, "rem") Await VerifyItemIsAbsentAsync(markup, "[rem]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping3() As Task Dim markup = <Text> Namespace Goo Module [Structure] Sub M() Dim x as Goo.$$ End Sub End Module End Namespace </Text>.Value Await VerifyItemExistsAsync(markup, "Structure") Await VerifyItemIsAbsentAsync(markup, "[Structure]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeKeywordEscaping() As Task Dim markup = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;$$ Class C End Class </Text>.Value Await VerifyItemExistsAsync(markup, "class") Await VerifyItemIsAbsentAsync(markup, "[class]") End Function <WorkItem(645898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645898")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EscapedKeywordAttributeCommit() As Task Dim markup = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;$$ Class C End Class </Text>.Value Dim expected = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;[class]( Class C End Class </Text>.Value Await VerifyProviderCommitAsync(markup, "class", expected, "("c) End Function <WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllMembersInEnumLocalAccess() As Task Dim markup = <Text> Class C Enum x a b c End Enum Sub M() Dim y = x.a y.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "a") Await VerifyItemExistsAsync(markup, "b") Await VerifyItemExistsAsync(markup, "c") Await VerifyItemExistsAsync(markup, "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadOnlyPropertiesPresentOnRightSideInObjectInitializer() As Task Dim text = <a>Class C Public Property Goo As Integer Public ReadOnly Property Bar As Integer Get Return 0 End Get End Property Sub M() Dim c As New C With { .Goo = .$$ End Sub End Class</a>.Value Await VerifyItemExistsAsync(text, "Goo") Await VerifyItemExistsAsync(text, "Bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeExplicitDeclaration_ExplicitOff() As Task Dim text = <Text> Option Explicit Off Class C Sub M() $$ Dim goo = 3 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeExplicitDeclaration_ExplicitOn() As Task Dim text = <Text> Option Explicit On Class C Sub M() $$ Dim goo = 3 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "goo") End Function <WorkItem(10572, "DevDiv_Projects/Roslyn")> <WorkItem(530595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530595")> <Fact> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableBeforeImplicitDeclaration() As Task Dim text = <Text> Option Explicit Off Class C Function M() as Integer $$ Return goo End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableInItsDeclaration() As Task ' "Dim goo As Integer = goo" is legal code while "Dim goo = goo" is not, but ' offer the local name on the right in either case because in the second ' case there's an error stating that goo needs to be explicitly typed and ' the user can then add the As clause. This mimics the behavior of ' "var x = x = 0" in C#. Dim text = <Text> Class C Sub M() Dim goo = $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableInItsDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = 4, bar = $$, baz = 5 End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeItsDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = $$, bar = 5 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableAfterDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = 5, bar = $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(545439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545439")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterReDim() As Task Dim text = <Text> Class C Sub M() Dim goo(10, 20) As Integer ReDim $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(545439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545439")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterReDimPreserve() As Task Dim text = <Text> Class C Sub M() Dim goo(10, 20) As Integer ReDim Preserve $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(546353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546353")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNamespaceDeclarationIntellisense() As Task Dim text = <Text> Namespace Goo.$$ Class C End Class</Text>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(531258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531258")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelsAfterOnErrorGoTo() As Task Dim code = <Code> Class C Sub M() On Error GoTo $$ label1: Dim x = 1 End Sub End Class</Code>.Value Await VerifyItemExistsAsync(code, "label1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAwaitableItem() As Task Dim code = <Code> Imports System.Threading.Tasks Class C ''' &lt;summary&gt; ''' Doc Comment! ''' &lt;/summary&gt; Async Function Goo() As Task Me.$$ End Function End Class</Code>.Value Dim description = $"<{VBFeaturesResources.Awaitable}> Function C.Goo() As Task Doc Comment!" Await VerifyItemWithMscorlib45Async(code, "Goo", description, LanguageNames.VisualBasic) End Function <WorkItem(550760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550760")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAwait() As Task Dim code = <Code> Imports System.Threading.Tasks Class SomeClass Public Async Sub goo() Await $$ End Sub Async Function Bar() As Task(Of Integer) Return Await Task.Run(Function() 42) End Function End Class</Code>.Value Await VerifyItemExistsAsync(code, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObsoleteItem() As Task Dim code = <Code> Imports System Class SomeClass &lt;Obsolete&gt; Public Sub Goo() $$ End Sub End Class</Code>.Value Await VerifyItemExistsAsync(code, "Goo", $"({VBFeaturesResources.Deprecated}) Sub SomeClass.Goo()") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpressionAfterYield() As Task Dim code = <Code> Class SomeClass Iterator Function Goo() As Integer Dim x As Integer Yield $$ End Function End Class </Code>.Value Await VerifyItemExistsAsync(code, "x") End Function <WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersOnDottingIntoUnboundType() As Task Dim code = <Code> Module Program Dim goo As RegistryKey Sub Main(args() As String) goo.$$ End Sub End Module </Code>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(611154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611154")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoOperators() As Task Await VerifyItemIsAbsentAsync( AddInsideMethod("String.$$"), "op_Equality") End Function <WorkItem(736891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736891")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInBinaryConditionalExpression() As Task Dim code = <Code> Module Program Sub Main(args() As String) args = If($$ End Sub End Module </Code>.Value Await VerifyItemExistsAsync(code, "args") End Function <WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInTopLevelFieldInitializer() As Task Dim code = <Code> Dim aaa = 1 Dim bbb = $$ </Code>.Value Await VerifyItemExistsAsync(code, "aaa") End Function #End Region #Region "SharedMemberSourceTests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation1() As Task Await VerifyItemIsAbsentAsync("System.Console.$$", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation2() As Task Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "System.Console.$$"), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation3() As Task Await VerifyItemIsAbsentAsync("Imports System.Console.$$", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation4() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", CreateContent("Class C ", "' Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation5() As Task Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = ""Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation6() As Task Await VerifyItemIsAbsentAsync("<System.Console.$$>", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInsideMethodBody() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInsideAccessorBody() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", " Property Prop As String", " Get", " Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldInitializer() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", " Dim d = Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMethods() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", "Private Shared Function Method() As Boolean", "End Function", " Dim d = $$", "")), "Method") End Function #End Region #Region "EditorBrowsableTests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar(x as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverriddenSymbolsFilteredFromCompletionList() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d as D d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class B Public Overridable Sub Goo(original As Integer) End Sub End Class Public Class D Inherits B Public Overrides Sub Goo(derived As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c = New C() c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class C Public Sub Goo() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d = new D() d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class B Public Sub Goo() End Sub End Class Public Class D Inherits B Public Overloads Sub Goo(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_HidingWithDifferentArgumentList() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d = new D() d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class B Public Sub Goo() End Sub End Class Public Class D Inherits B Public Sub Goo(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateNeverMethodsInBaseClass() As Task Dim markup = <Text><![CDATA[ Class Program Inherits B Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class B <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) Public Sub Goo(t As T) End Sub Public Sub Goo(i as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t as T) End Sub Public Sub Goo(i as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(i As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(i As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) Public Sub Goo(t As T) End Sub Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo Public Property Bar As Integer <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Get Return 5 End Get <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_MixedOverloads1() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_MixedOverloads2() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_IgnoreBaseClassBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo Inherits Bar End Class <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Bar End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_CrossLanguage_VBtoCS_Always() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x As $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.CSharp, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_CrossLanguage_VBtoCS_Never() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x As $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=0, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.CSharp, hideAdvancedMembers:=False) End Function #End Region #Region "Inherits/Implements Tests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInherits() As Task Const markup = " Public Class Base End Class Class Derived Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "Base") Await VerifyItemIsAbsentAsync(markup, "Derived") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInheritsDotIntoClass() As Task Const markup = " Public Class Base Public Class Nest End Class End Class Class Derived Inherits Base.$$ End Class " Await VerifyItemExistsAsync(markup, "Nest") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplements() As Task Const markup = " Public Interface IGoo End Interface Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IGoo") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AliasedInterfaceAfterImplements() As Task Const markup = " Imports IAlias = IGoo Public Interface IGoo End Interface Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IAlias") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AliasedNamespaceAfterImplements() As Task Const markup = " Imports AliasedNS = NS1 Namespace NS1 Public Interface IGoo End Interface Class C Implements $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedNS") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedClassAfterInherits() As Task Const markup = " Imports AliasedClass = Base Public Class Base End Interface Class C Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "AliasedClass") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedNamespaceAfterInherits() As Task Const markup = " Imports AliasedNS = NS1 Namespace NS1 Public Class Base End Interface Class C Inherits $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedNS") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedClassAfterInherits2() As Task Const markup = " Imports AliasedClass = NS1.Base Namespace NS1 Public Class Base End Interface Class C Inherits $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedClass") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplementsComma() As Task Const markup = " Public Interface IGoo End Interface Public Interface IBar End interface Class C Implements IGoo, $$ End Class " Await VerifyItemExistsAsync(markup, "IBar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_ClassContainingInterface() As Task Const markup = " Public Class Base Public Interface Nest End Class End Class Class Derived Implements $$ End Class " Await VerifyItemExistsAsync(markup, "Base") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_NoClassNotContainingInterface() As Task Const markup = " Public Class Base End Class Class Derived Implements $$ End Class " Await VerifyItemIsAbsentAsync(markup, "Base") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_GenericClass() As Task Const markup = " Public Class base(Of T) End Class Public Class derived Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "base", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_GenericInterface() As Task Const markup = " Public Interface IGoo(Of T) End Interface Public Class bar Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IGoo", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(546610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546610")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_IncompleteClassDeclaration() As Task Const markup = " Public Interface IGoo End Interface Public Interface IBar End interface Class C Implements IGoo,$$ " Await VerifyItemExistsAsync(markup, "IBar") End Function <WorkItem(546611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546611")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_NotNotInheritable() As Task Const markup = " Public NotInheritable Class D End Class Class C Inherits $$ " Await VerifyItemIsAbsentAsync(markup, "D") End Function <WorkItem(546802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546802")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_KeywordIdentifiersShownUnescaped() As Task Const markup = " Public Class [Inherits] End Class Class C Inherits $$ " Await VerifyItemExistsAsync(markup, "Inherits") End Function <WorkItem(546802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546802")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_KeywordIdentifiersCommitEscaped() As Task Const markup = " Public Class [Inherits] End Class Class C Inherits $$ " Const expected = " Public Class [Inherits] End Class Class C Inherits [Inherits]. " Await VerifyProviderCommitAsync(markup, "Inherits", expected, "."c) End Function <WorkItem(546801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546801")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_Modules() As Task Const markup = " Module Module1 Sub Main() End Sub End Module Module Module2 Class Bx End Class End Module Class Max Class Bx End Class End Class Class A Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "Module2") Await VerifyItemIsAbsentAsync(markup, "Module1") End Function <WorkItem(530726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530726")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_DoNotShowNamespaceWithNoApplicableClasses() As Task Const markup = " Namespace N Module M End Module End Namespace Class C Inherits $$ End Class " Await VerifyItemIsAbsentAsync(markup, "N") End Function <WorkItem(530725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530725")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_CheckStructContents() As Task Const markup = " Namespace N Public Structure S1 Public Class B End Class End Structure Public Structure S2 End Structure End Namespace Class C Inherits N.$$ End Class " Await VerifyItemIsAbsentAsync(markup, "S2") Await VerifyItemExistsAsync(markup, "S1") End Function <WorkItem(530724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530724")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_NamespaceContainingInterface() As Task Const markup = " Namespace N Interface IGoo End Interface End Namespace Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "N") End Function <WorkItem(531256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531256")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_OnlyInterfacesForInterfaceInherits1() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface IGoo Inherits $$ " Await VerifyItemExistsAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_InterfaceCircularInheritance() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface A(Of T) Inherits A(Of A(Of T)) Interface B Inherits $$ End Interface End Interface " Await VerifyItemExistsAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(531256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531256")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_OnlyInterfacesForInterfaceInherits2() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface IGoo Implements $$ " Await VerifyItemIsAbsentAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(547291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547291")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_CommitGenericOnParen() As Task Const markup = " Class G(Of T) End Class Class DG Inherits $$ End Class " Dim expected = " Class G(Of T) End Class Class DG Inherits G( End Class " Await VerifyProviderCommitAsync(markup, "G(Of " & s_unicodeEllipsis & ")", expected, "("c) End Function <WorkItem(579186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579186")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplementsWithCircularInheritance() As Task Const markup = " Interface I(Of T) End Interface Class C(Of T) Class D Inherits C(Of D) Implements $$ End Class End Class " Await VerifyItemExistsAsync(markup, "I", displayTextSuffix:="(Of …)") End Function <WorkItem(622563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622563")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_CommitNonGenericOnParen() As Task Const markup = " Class G End Class Class DG Inherits $$ End Class " Dim expected = " Class G End Class Class DG Inherits G( End Class " Await VerifyProviderCommitAsync(markup, "G", expected, "("c) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInheritsWithCircularInheritance() As Task Const markup = " Class B End Class Class C(Of T) Class D Inherits C(Of D) Inherits $$ End Class End Class " Await VerifyItemExistsAsync(markup, "B") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_ClassesInsideSealedClasses() As Task Const markup = " Public NotInheritable Class G Public Class H End Class End Class Class SomeClass Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "G") End Function <WorkItem(638762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638762")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_ClassWithinNestedStructs() As Task Const markup = " Structure somestruct Structure Inner Class FinallyAClass End Class End Structure End Structure Class SomeClass Inherits $$ End " Await VerifyItemExistsAsync(markup, "somestruct") End Function #End Region <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExtensionMethodsOffered() As Task Dim markup = <Text><![CDATA[ Imports System.Runtime.CompilerServices Class Program Sub Main(args As String()) Me.$$ End Sub End Class Module Extensions <Extension> Sub Goo(program As Program) End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") End Function <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExtensionMethodsOffered2() As Task Dim markup = <Text><![CDATA[ Imports System.Runtime.CompilerServices Class Program Sub Main(args As String()) Dim a = new Program() a.$$ End Sub End Class Module Extensions <Extension> Sub Goo(program As Program) End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") End Function <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLinqExtensionMethodsOffered() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Class Program Sub Main(args As String()) Dim a as IEnumerable(Of Integer) = Nothing a.$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Average") End Function <WorkItem(884060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884060")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionOffTypeParameter() As Task Dim markup = <Text><![CDATA[ Module Program Function bar(Of T As Object)() As T T.$$ End Function End Moduleb End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAvailableInBothLinkedFiles() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C Dim x as integer sub goo() $$ end sub end class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences=" True" AssemblyName="Proj2"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) C.x As Integer") End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAvailableInOneLinkedFile() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="GOO=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #If GOO Then Dim x as integer #End If Sub goo() $$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"({FeaturesResources.field}) C.x As Integer" + vbCrLf + vbCrLf + String.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available) + vbCrLf + String.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available) + vbCrLf + vbCrLf + FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <WorkItem(13161, "https://github.com/dotnet/roslyn/issues/13161")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitGenericOnTab() As Task Dim text = <code> Class G(Of T) End Class Class DG Function Bar() as $$ End Class</code>.Value Dim expected = <code> Class G(Of T) End Class Class DG Function Bar() as G(Of End Class</code>.Value Await VerifyProviderCommitAsync(text, "G(Of …)", expected, Nothing) End Function <WorkItem(909121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909121")> <WorkItem(2048, "https://github.com/dotnet/roslyn/issues/2048")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitGenericOnParen() As Task Dim text = <code> Class G(Of T) End Class Class DG Function Bar() as $$ End Class</code>.Value Dim expected = <code> Class G(Of T) End Class Class DG Function Bar() as G( End Class</code>.Value Await VerifyProviderCommitAsync(text, "G(Of …)", expected, "("c) End Function <WorkItem(668159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/668159")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributesShownWithBraceCompletionActive() As Task Dim text = <code><![CDATA[ Imports System <$$> Class C End Class Class GooAttribute Inherits Attribute End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescriptionInAliasedType() As Task Dim text = <code><![CDATA[ Imports IAlias = IGoo Class C Dim x as IA$$ End Class ''' <summary> ''' summary for interface IGoo ''' </summary> Interface IGoo Sub Bar() End Interface ]]></code>.Value Await VerifyItemExistsAsync(text, "IAlias", expectedDescriptionOrNull:="Interface IGoo" + vbCrLf + "summary for interface IGoo") End Function <WorkItem(842049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842049")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMergedNamespace1() As Task Dim text = <code><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class D End Class End Namespace Module M Dim c As X.C Dim d As X.D Dim e As X.$$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "C") Await VerifyItemExistsAsync(text, "D") End Function <WorkItem(842049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842049")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMergedNamespace2() As Task Dim text = <code><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class D End Class End Namespace Module M Dim c As X.C Dim d As X.D Sub Goo() X.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "C") Await VerifyItemExistsAsync(text, "D") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_EmptyNameSpan_TopLevel() As Task Dim source = <code><![CDATA[ Namespace $$ End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_EmptyNameSpan_Nested() As Task Dim source = <code><![CDATA[ Namespace System Namespace $$ End Namespace End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_TopLevelNoPeers() As Task Dim source = <code><![CDATA[ Imports System; Namespace $$ ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "String") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_TopLevelWithPeer() As Task Dim source = <code><![CDATA[ Namespace A End Namespace Namespace $$ ]]></code>.Value Await VerifyItemExistsAsync(source, "A") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_NestedWithNoPeers() As Task Dim source = <code><![CDATA[ Namespace A Namespace $$ End Namespace ]]></code>.Value Await VerifyNoItemsExistAsync(source) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_NestedWithPeer() As Task Dim source = <code><![CDATA[ Namespace A Namespace B End Namespace Namespace $$ End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_ExcludesCurrentDeclaration() As Task Dim source = <code><![CDATA[Namespace N$$S]]></code>.Value Await VerifyItemIsAbsentAsync(source, "NS") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_WithNested() As Task Dim source = <code><![CDATA[ Namespace A Namespace $$ Namespace B End Namespace End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_WithNestedAndMatchingPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A Namespace $$ Namespace B End Namespace End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_InnerCompletionPosition() As Task Dim source = <code><![CDATA[ Namespace Sys$$tem End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_IncompleteDeclaration() As Task Dim source = <code><![CDATA[ Namespace A Namespace B Namespace $$ Namespace C1 End Namespace End Namespace Namespace B.C2 End Namespace End Namespace Namespace A.B.C3 End Namespace ]]></code>.Value ' Ideally, all the C* namespaces would be recommended but, because of how the parser ' recovers from the missing end statement, they end up with the following qualified names... ' ' C1 => A.B.?.C1 ' C2 => A.B.B.C2 ' C3 => A.A.B.C3 ' ' ...none of which are found by the current algorithm. Await VerifyItemIsAbsentAsync(source, "C1") Await VerifyItemIsAbsentAsync(source, "C2") Await VerifyItemIsAbsentAsync(source, "C3") Await VerifyItemIsAbsentAsync(source, "A") ' Because of the above, B does end up in the completion list ' since A.B.B appears to be a peer of the New declaration Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_NoPeers() As Task Dim source = <code><![CDATA[Namespace A.$$]]></code>.Value Await VerifyNoItemsExistAsync(source) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_TopLevelWithPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A.$$ ]]></code>.Value Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_NestedWithPeer() As Task Dim source = <code><![CDATA[ Namespace A Namespace B.C End Namespace Namespace B.$$ End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") Await VerifyItemExistsAsync(source, "C") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_WithNested() As Task Dim source = <code><![CDATA[ Namespace A.$$ Namespace B End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_WithNestedAndMatchingPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A.$$ Namespace B End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_InnerCompletionPosition() As Task Dim source = <code><![CDATA[ Namespace Sys$$tem.Runtime End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_IncompleteDeclaration() As Task Dim source = <code><![CDATA[ Namespace A Namespace B Namespace C.$$ Namespace C.D1 End Namespace End Namespace Namespace B.C.D2 End Namespace End Namespace Namespace A.B.C.D3 End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") Await VerifyItemIsAbsentAsync(source, "C") ' Ideally, all the D* namespaces would be recommended but, because of how the parser ' recovers from the end statement, they end up with the following qualified names... ' ' D1 => A.B.C.C.?.D1 ' D2 => A.B.B.C.D2 ' D3 => A.A.B.C.D3 ' ' ...none of which are found by the current algorithm. Await VerifyItemIsAbsentAsync(source, "D1") Await VerifyItemIsAbsentAsync(source, "D2") Await VerifyItemIsAbsentAsync(source, "D3") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_OnKeyword() As Task Dim source = <code><![CDATA[ Name$$space System End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "System") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_OnNestedKeyword() As Task Dim source = <code><![CDATA[ Namespace System Name$$space Runtime End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(925469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925469")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitWithCloseBracketLeaveOpeningBracket1() As Task Dim text = <code><![CDATA[ Class Await Sub Goo() Dim x = new [Awa$$] End Sub End Class]]></code>.Value Dim expected = <code><![CDATA[ Class Await Sub Goo() Dim x = new [Await] End Sub End Class]]></code>.Value Await VerifyProviderCommitAsync(text, "Await", expected, "]"c) End Function <WorkItem(925469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925469")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitWithCloseBracketLeavesOpeningBracket2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new [Cla$$] End Sub End Class]]></code>.Value Dim expected = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new [Class] End Sub End Class]]></code>.Value Await VerifyProviderCommitAsync(text, "Class", expected, "]"c) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletion() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new Object() x?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletion2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new Object() x?.ToString()?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletionForNullableParameterSymbols_1() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo(dt As System.DateTime?) dt?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Day") Await VerifyItemIsAbsentAsync(text, "Value") End Function <WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletionForNullableParameterSymbols_2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo(dt As System.DateTime?) dt.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Value") Await VerifyItemIsAbsentAsync(text, "Day") End Function <WorkItem(1041269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041269")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestHidePropertyBackingFieldAndEventsAtExpressionLevel() As Task Dim text = <code><![CDATA[ Imports System Class C Property p As Integer = 15 Event e as EventHandler Sub f() Dim x = $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "_p") Await VerifyItemIsAbsentAsync(text, "e") End Function <WorkItem(1041269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041269")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableForConditionalAccess() As Task Dim text = <code><![CDATA[ Class C Sub Goo() Dim x as Integer? = Nothing x?.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "GetTypeCode") Await VerifyItemIsAbsentAsync(text, "HasValue") End Function <WorkItem(1079694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDontThrowForNullPropagatingOperatorInErase() As Task Dim text = <code><![CDATA[ Module Program Sub Main() Dim x?(1) Erase x?.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUnwrapNullableForConditionalFromStructure() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As A x?.$$b?.c End Sub End Module Structure A Public b As B End Structure Public Class B Public c As C End Class Public Class C End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "b") Await VerifyItemIsAbsentAsync(text, "c") End Function <WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWithinChainOfConditionalAccess() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As A x?.$$b?.c End Sub End Module Class A Public b As B End Class Public Class B Public c As C End Class Public Class C End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "b") Await VerifyItemIsAbsentAsync(text, "c") End Function <WorkItem(1079694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDontThrowForNullPropagatingOperatorOnTypeParameter() As Task Dim text = <code><![CDATA[ Module Program Sub Goo(Of T)(x As T) x?.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(1079723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079723")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionAfterNullPropagatingOperatingInWithBlock() As Task Dim text = <code><![CDATA[ Option Strict On Module Program Sub Main() Dim s = "" With s ?.$$ End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext1() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext2() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext3() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext4() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext5() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext6() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext7() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext8() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext9() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(Me.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext10() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(Me.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext11() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyClass.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext12() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyClass.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext13() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyBase.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext14() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyBase.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext15() As Task Dim text = <code><![CDATA[ Class C Shared Sub Goo() End Sub Sub Bar() End Sub End Class Class D Inherits C Sub M() Dim s = NameOf(MyBase.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext16() As Task Dim text = <code><![CDATA[ Class C Shared Sub Goo() End Sub Sub Bar() End Sub End Class Class D Inherits C Sub M() Dim s = NameOf(MyBase.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(46472, "https://github.com/dotnet/roslyn/issues/46472")> Public Async Function TestAllowCompletionInNameOfArgumentContext17() As Task Dim text = <code><![CDATA[ Public Class C Event Bar() Public Sub Baz() Dim s = NameOf($$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInInterpolationExpressionContext1() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{$$}" End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInInterpolationExpressionContext2() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{$$ ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionInInterpolationAlignmentContext() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{x,$$}" End Sub End Class ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionInInterpolationFormatContext() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{x:$$}" End Sub End Class ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(1293, "https://github.com/dotnet/roslyn/issues/1293")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredAfterDotInWithAfterNumericLiteral() As Task Dim text = <code><![CDATA[ Class Program Public Property P As Long Sub M() With Me .P = 122 .$$ End With End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M", usePreviousCharAsTrigger:=True) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes1() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) System?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes2() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Console?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes3() As Task Dim text = <code><![CDATA[ Imports a = System Module Program Sub Main(args As String()) a?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(3086, "https://github.com/dotnet/roslyn/issues/3086")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersOffInstanceInColorColor() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x = C.$$ End Sub Dim C As New C() End Module Class C Public X As Integer = 1 Public Shared Y As Integer = 2 End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "X") Await VerifyItemExistsAsync(text, "Y") End Function <WorkItem(3086, "https://github.com/dotnet/roslyn/issues/3086")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotSharedMembersOffAliasInColorColor() As Task Dim text = <code><![CDATA[ Imports B = C Module Program Sub Main(args As String()) Dim x = B.$$ End Sub Dim B As New B() End Module Class C Public X As Integer = 1 Public Shared Y As Integer = 2 End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "X") Await VerifyItemIsAbsentAsync(text, "Y") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType() As Task Dim text = <code><![CDATA[ MustInherit Class Test Private _field As Integer NotInheritable Class InnerTest Inherits Test Sub SomeTest() Dim x = $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "_field") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType2() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() $$ ' M recommended and accessible End Sub Class NN Sub Test2() ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType3() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() ' M recommended and accessible End Sub Class NN Sub Test2() $$ ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType4() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() M() ' M recommended and accessible End Sub Class NN Inherits N Sub Test2() $$ ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType5() As Task Dim text = <code><![CDATA[ Class D Public Sub Q() End Sub End Class Class C(Of T) Inherits D Class N Sub Test() $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Q") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType6() As Task Dim text = <code><![CDATA[ Class Base(Of T) Public X As Integer End Class Class Derived Inherits C(Of Integer) Class Nested Sub Test() $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "X") End Function <WorkItem(4900, "https://github.com/dotnet/roslyn/issues/4090")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceMembersWhenDottingIntoType() As Task Dim text = <code><![CDATA[ Class Instance Public Shared x as Integer Public y as Integer End Class Class Program Sub Goo() Instance.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "y") Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(4900, "https://github.com/dotnet/roslyn/issues/4090")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoSharedMemberWhenDottingIntoInstance() As Task Dim text = <code><![CDATA[ Class Instance Public Shared x as Integer Public y as Integer End Class Class Program Sub Goo() Dim x = new Instance() x.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") Await VerifyItemExistsAsync(text, "y") End Function <WorkItem(4136, "https://github.com/dotnet/roslyn/issues/4136")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoValue__WhenDottingIntoEnum() As Task Dim text = <code><![CDATA[ Enum E A End Enum Class Program Sub Goo() E.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "A") Await VerifyItemIsAbsentAsync(text, "value__") End Function <WorkItem(4136, "https://github.com/dotnet/roslyn/issues/4136")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoValue__WhenDottingIntoLocalOfEnumType() As Task Dim text = <code><![CDATA[ Enum E A End Enum Class Program Sub Goo() Dim x = E.A x.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "value__") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SharedProjectFieldAndPropertiesTreatedAsIdentical() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="ONE=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #if ONE Then Public x As Integer #endif #if TWO Then Public Property x as Integer #endif Sub goo() x$$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2" PreprocessorSymbols="TWO=True"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"({ FeaturesResources.field }) C.x As Integer" Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedProjectFieldAndPropertiesTreatedAsIdentical2() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="ONE=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #if TWO Then Public x As Integer #endif #if ONE Then Public Property x as Integer #endif Sub goo() x$$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2" PreprocessorSymbols="TWO=True"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"Property C.x As Integer" Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <WorkItem(4405, "https://github.com/dotnet/roslyn/issues/4405")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function VerifyDelegateEscapedWhenCommitted() As Task Dim text = <code><![CDATA[ Imports System Module Module1 Sub Main() Dim x As {0} End Sub End Module ]]></code>.Value Await VerifyProviderCommitAsync(markupBeforeCommit:=String.Format(text, "$$"), itemToCommit:="Delegate", expectedCodeAfterCommit:=String.Format(text, "[Delegate]"), commitChar:=Nothing) End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInExpressionContext1() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) args.Select($$) End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInExpressionContext2() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInGetType() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) GetType($$) End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInTypeOf() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s = TypeOf args Is $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInReturnTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function x() as $$ End Function End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInFieldTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim x as $$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemDelegateInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Delegate") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInExpressionContext1() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) args.Select($$) End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInExpressionContext2() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInGetType() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) GetType($$) End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInTypeOf() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s = TypeOf args Is $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInReturnTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function x() as $$ End Function End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInFieldTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim x as $$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemDelegateInExpressionContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Delegate") End Function <WorkItem(4750, "https://github.com/dotnet/roslyn/issues/4750")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalAccessInWith1() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim s As String With s 1: Console.WriteLine(If(?.$$, -1)) Console.WriteLine() End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(4750, "https://github.com/dotnet/roslyn/issues/4750")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalAccessInWith2() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim s As String With s 1: Console.WriteLine(If(?.Length, -1)) ?.$$ Console.WriteLine() End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(3290, "https://github.com/dotnet/roslyn/issues/3290")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDotAfterArray() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim x = {1}.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LocalInForLoop() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As Integer For $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeConstLocalInForLoop() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim const x As Integer For $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeConstFieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program Const x As Integer = 0 Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeReadOnlyFieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program ReadOnly x As Integer Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function FieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program Dim x As Integer Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumMembers() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Do Until (System.Console.ReadKey.Key = System.ConsoleKey.$$ Loop End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "A") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleElements() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim t = (Alice:=1, Item2:=2, ITEM3:=3, 4, 5, 6, 7, 8, Bob:=9) t.$$ End Sub End Module Namespace System Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) Public Dim Rest As TRest Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub Public Overrides Function ToString() As String Return "" End Function Public Overrides Function GetHashCode As Integer Return 0 End Function Public Overrides Function CompareTo(value As Object) As Integer Return 0 End Function Public Overrides Function GetType As Type Return Nothing End Function End Structure End Namespace ]]></code>.Value Await VerifyItemExistsAsync(text, "Alice") Await VerifyItemExistsAsync(text, "Bob") Await VerifyItemExistsAsync(text, "CompareTo") Await VerifyItemExistsAsync(text, "Equals") Await VerifyItemExistsAsync(text, "GetHashCode") Await VerifyItemExistsAsync(text, "GetType") For index = 2 To 8 Await VerifyItemExistsAsync(text, "Item" + index.ToString()) Next Await VerifyItemExistsAsync(text, "ToString") Await VerifyItemIsAbsentAsync(text, "Item1") Await VerifyItemIsAbsentAsync(text, "Item9") Await VerifyItemIsAbsentAsync(text, "Rest") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function WinformsInstanceMembers() As Task ' Setting the the preprocessor symbol _MyType=WindowsForms will cause the ' compiler to automatically generate the My Template. See ' GroupClassTests.vb for the compiler layer equivalent of these tests. Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="_MyType=WindowsForms"> <Document name="Form.vb"> <![CDATA[ Namespace Global.System.Windows.Forms Public Class Form Implements IDisposable Public Sub InstanceMethod() End Sub Public Shared Sub SharedMethod() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub Public ReadOnly Property IsDisposed As Boolean Get Return False End Get End Property End Class End Namespace ]]></Document> <Document name="types.vb"><![CDATA[ Imports System Namespace Global.WindowsApplication1 Public Class Form2 Inherits System.Windows.Forms.Form End Class End Namespace Namespace Global.WindowsApplication1 Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Goo() Form2.$$ End Sub End Class End Namespace ]]></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, exportProvider:=ExportProvider) Dim document = workspace.CurrentSolution.GetDocument(workspace.DocumentWithCursor.Id) Dim position = workspace.DocumentWithCursor.CursorPosition.Value Await CheckResultsAsync(document, position, "InstanceMethod", expectedDescriptionOrNull:=Nothing, usePreviousCharAsTrigger:=False, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionModeItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, inlineDescription:=Nothing, isComplexTextEdit:=Nothing, matchingFilters:=Nothing, flags:=Nothing) Await CheckResultsAsync(document, position, "SharedMethod", expectedDescriptionOrNull:=Nothing, usePreviousCharAsTrigger:=False, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionModeItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, inlineDescription:=Nothing, isComplexTextEdit:=Nothing, matchingFilters:=Nothing, flags:=Nothing) End Using End Function <WorkItem(22002, "https://github.com/dotnet/roslyn/issues/22002")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DoNotCrashInTupleAlias() As Task Dim text = <code><![CDATA[ Imports Boom = System.Collections.Generic.List(Of ($$) '<---put caret between brackets. Public Module Module1 Public Sub Main() End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "System") End Function Private Shared Function CreateThenIncludeTestCode(lambdaExpressionString As String, methodDeclarationString As String) As String Dim template = " Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Linq.Expressions Namespace ThenIncludeIntellisenseBug Class Program Shared Sub Main(args As String()) Dim registrations = New List(Of Registration)().AsQueryable() Dim reg = registrations.Include(Function(r) r.Activities).ThenInclude([1]) End Sub End Class Friend Class Registration Public Property Activities As ICollection(Of Activity) End Class Public Class Activity Public Property Task As Task End Class Public Class Task Public Property Name As String End Class Public Interface IIncludableQueryable(Of Out TEntity, Out TProperty) Inherits IQueryable(Of TEntity) End Interface Public Module EntityFrameworkQuerybleExtensions <System.Runtime.CompilerServices.Extension> Public Function Include(Of TEntity, TProperty)( source As IQueryable(Of TEntity), navigationPropertyPath As Expression(Of Func(Of TEntity, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function [2] End Module End Namespace" Return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenInclude() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeNoExpression() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Func(Of TPreviousProperty, TProperty)) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Func(Of TPreviousProperty, TProperty)) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgument() As Task Dim source = CreateThenIncludeTestCode("0, Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentAndMultiArgumentLambda() As Task Dim source = CreateThenIncludeTestCode("0, Function(a, b, c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentNoOverlap() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.Task, Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty)), anotherNavigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() As Task Dim source = CreateThenIncludeTestCode("0, Function(a, b, c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemIsAbsentAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeGenericAndNoGenericOverloads() As Task Dim source = CreateThenIncludeTestCode("Function(c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Func(Of Activity, Task)) As IIncludableQueryable(Of Registration, Task) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeNoGenericOverloads() As Task Dim source = CreateThenIncludeTestCode("Function(c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Func(Of Activity, Task)) As IIncludableQueryable(Of Registration, Task) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Expression(Of Func(Of ICollection(Of Activity), Activity))) As IIncludableQueryable(Of Registration, Activity) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionForLambdaWithOverloads() As Task Dim source = <code><![CDATA[ Imports System.Linq.Expressions Imports System.Collections Imports System Imports System.Collections.Generic Namespace VBTest Public Class SomeItem Public A As String Public B As Integer End Class Class SomeCollection(Of T) Inherits List(Of T) Public Overridable Function Include(path As String) As SomeCollection(Of T) Return Nothing End Function End Class Module Extensions <System.Runtime.CompilerServices.Extension> Public Function Include(Of T, TProperty)(ByVal source As IList(Of T), path As Expression(Of Func(Of T, TProperty))) As IList(Of T) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function Include(ByVal source As IList, path As String) As IList Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function Include(Of T)(ByVal source As IList(Of T), path As String) As IList(Of T) Return Nothing End Function End Module Class Program Sub M(c As SomeCollection(Of SomeItem)) Dim a = From m In c.Include(Function(t) t.$$) End Sub End Class End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads2() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As String) End Sub Sub Test() M(Sub(a) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads3() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As Action(Of String)) End Sub Sub Test() M(Sub(a as Integer) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads4() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As Action(Of String)) End Sub Sub Test() M(Sub(a) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(y:=Sub(x) x.$$ End Sub) End Sub Sub M(Optional x As Integer = 0, Optional y As Action(Of String) = Nothing) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(z:=Sub(x) x.$$ End Sub) End Sub Sub M(x As Integer, y As Integer, z As Action(Of String)) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameterWithDifferentCasing() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(Z:=Sub(x) x.$$ End Sub) End Sub Sub M(x As Integer, y As Integer, z As Action(Of String)) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithNonFunctionsAsArguments() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Sub(b) b.$$ End Sub Sub Goo(configure As Action(Of Builder)) Dim builder = New Builder() configure(builder) End Sub End Class Class Builder Public Property Something As Integer End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Something") Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithDelegatesAsArguments() As Task Dim source = <code><![CDATA[ Imports System Module Module2 Class Program Public Delegate Sub Delegate1(u As Uri) Public Delegate Sub Delegate2(g As Guid) Public Sub M(d As Delegate1) End Sub Public Sub M(d As Delegate2) End Sub Public Sub Test() M(Sub(d) d.$$) End Sub End Class End Module ]]></code>.Value ' Guid Await VerifyItemExistsAsync(source, "ToByteArray") ' Uri Await VerifyItemExistsAsync(source, "AbsoluteUri") Await VerifyItemExistsAsync(source, "Fragment") Await VerifyItemExistsAsync(source, "Query") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithDelegatesAndReversingArguments() As Task Dim source = <code><![CDATA[ Imports System Module Module2 Class Program Public Delegate Sub Delegate1(Of T1, T2)(t2 As T2, t1 As T1) Public Delegate Sub Delegate2(Of T1, T2)(t2 As T2, a As Integer, t1 As T1) Public Sub M(d As Delegate1(Of Uri, Guid)) End Sub Public Sub M(d As Delegate2(Of Uri, Guid)) End Sub Public Sub Test() M(Sub(d) d.$$) End Sub End Class End Module ]]></code>.Value ' Guid Await VerifyItemExistsAsync(source, "ToByteArray") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "AbsoluteUri") Await VerifyItemIsAbsentAsync(source, "Fragment") Await VerifyItemIsAbsentAsync(source, "Query") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")> <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function CompletionInsideMethodWithParamsBeforeParams() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Sub(b) b.$$) End Sub Sub Goo(action As Action(Of Builder), ParamArray otherActions() As Action(Of AnotherBuilder)) End Sub End Class Class Builder Public Something As Integer End Class Class AnotherBuilder Public AnotherSomething As Integer End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "AnotherSomething") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") Await VerifyItemExistsAsync(source, "Something") End Function <WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")> <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function CompletionInsideMethodWithParamsInParams() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Nothing, Nothing, Sub(b) b.$$) End Sub Sub Goo(action As Action(Of Builder), ParamArray otherActions() As Action(Of AnotherBuilder)) End Sub End Class Class Builder Public Something As Integer End Class Class AnotherBuilder Public AnotherSomething As Integer End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Something") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") Await VerifyItemExistsAsync(source, "AnotherSomething") End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestTargetTypeFilterWithExperimentEnabled() As Task TargetTypedCompletionFilterFeatureFlag = True Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "intField", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.FieldFilter, FilterSet.TargetTypedFilter}) End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestNoTargetTypeFilterWithExperimentDisabled() As Task TargetTypedCompletionFilterFeatureFlag = False Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "intField", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.FieldFilter}) End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestTargetTypeFilter_NotOnObjectMembers() As Task TargetTypedCompletionFilterFeatureFlag = True Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.MethodFilter}) 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.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders <UseExportProvider> Public Class SymbolCompletionProviderTests Inherits AbstractVisualBasicCompletionProviderTests Private Const s_unicodeEllipsis = ChrW(&H2026) Friend Overrides Function GetCompletionProviderType() As Type Return GetType(SymbolCompletionProvider) End Function #Region "StandaloneNamespaceAndTypeSourceTests" Private Async Function VerifyNSATIsAbsentAsync(markup As String) As Task ' Verify namespace 'System' is absent Await VerifyItemIsAbsentAsync(markup, "System") ' Verify type 'String' is absent Await VerifyItemIsAbsentAsync(markup, "String") End Function Private Async Function VerifyNSATExistsAsync(markup As String) As Task ' Verify namespace 'System' is absent Await VerifyItemExistsAsync(markup, "System") ' Verify type 'String' is absent Await VerifyItemExistsAsync(markup, "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEmptyFile() As Task Await VerifyNSATIsAbsentAsync("$$") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEmptyFileWithImports() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", "$$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As $$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As { II, $$")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As $$)")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeConstraint4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", "Class A(Of T As { II, $$})")) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements $$.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements3() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As A Implements I.Method, $$.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method() As $$ Implements II.Method"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAs3() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", CreateContent("Class A", " Function Method(ByVal args As $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAsNew() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d As New $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGetType1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = GetType($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeOfIs() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TypeOf d Is $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObjectCreation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = New $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayCreation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d() = New $$() {"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CType(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TryCast(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = DirectCast(obj, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayType() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d() as $$("))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableType() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as $$?"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList1() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", CreateContent("Class A(Of $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList2() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", CreateContent("Class A(Of T, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as D(Of $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentList4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d as D(Of A, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInferredFieldInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim anonymousCust2 = New With {Key $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedFieldInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim anonymousCust = New With {.Name = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInitializer() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReturnStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Return $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIfStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("If $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestIfStatement2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("If Var1 Then", "Else If $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCatchFilterClause() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Try", "Catch ex As Exception when $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestErrorStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Error $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Select $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSelectStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Select Case $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSimpleCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case 1, $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case $$ To")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case 1 To $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRelationalCaseClause1() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case Is > $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRelationalCaseClause2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("Select T", "Case >= $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSyncLockStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("SyncLock $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileOrUntilClause1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Do While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileOrUntilClause2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Do Until $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhileStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = 1 To $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForStepClause() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For i = 1 To 10 Step $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestForEachStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("For Each I in $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUsingStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Using $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestThrowStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Throw $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAssignmentStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$ = a"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAssignmentStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("a = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCallStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Call $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCallStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(1)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("AddHandler $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("AddHandler T.Event, AddressOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("RemoveHandler $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAddRemoveHandlerStatement4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("RemoveHandler T.Event, AddressOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWithStatement() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("With $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestParenthesizedExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = ($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeOfIs2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = TypeOf $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMemberAccessExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$.Name"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMemberAccessExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$!Name"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvocationExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(1)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTypeArgumentExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("$$(Of Integer)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast4() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CType($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast5() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = TryCast($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCast6() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = DirectCast($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBuiltInCase() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = CInt($$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = $$ + d"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = d + $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUnaryExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = +$$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryConditionExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If($$,"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestBinaryConditionExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If($$, a, b"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, $$, c"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTernaryConditionExpression3() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = If(a, b, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSingleArgument() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("D($$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNamedArgument() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("D(Name := $$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeArgument1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a($$ To 10)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestRangeArgument2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a(0 To $$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionRangeVariable() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From var in $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpressionRangeVariable() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From var In collection Let b = $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFunctionAggregation() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In col Aggregate o In c.o Into an = Any($$)"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWhereQueryOperator() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In col Where $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionWhileQueryOperator1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim customerList = From c In cust Order By c.C Skip While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionWhileQueryOperator2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim customerList = From c In cust Order By c.C Take While $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionQueryOperator1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In cust Skip $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestPartitionQueryOperator2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From c In cust Take $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestJoinCondition1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim p1 = From p In P Join d In Desc On $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestJoinCondition2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim p1 = From p In P Join d In Desc On p.P Equals $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOrdering() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim a = From b In books Order By $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestXmlEmbeddedExpression() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim book As XElement = <book isbn=<%= $$ %>></book>"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNextStatement1() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("For i = 1 To 10", "Next $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNextStatement2() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("For i = 1 To 10", "Next i, $$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEraseStatement1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Erase $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEraseStatement2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Erase i, $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionInitializer1() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = new List(Of Integer) from { $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCollectionInitializer2() As Task Await VerifyNSATExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = { $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestStringLiteral() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = ""$$"""))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestComment1() As Task Await VerifyNSATIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("' $$"))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestComment2() As Task Await VerifyNSATExistsAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("'", "$$")))) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInactiveRegion1() As Task Await VerifyNSATIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod( CreateContent("#IF False Then", " $$")))) End Function #Region "Tests that verify namespaces and types separately" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAliasImportsClause1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports T = $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports T = $$"), "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAliasImportsClause2() As Task Await VerifyItemExistsAsync("Imports $$ = S", "System") Await VerifyItemIsAbsentAsync("Imports $$ = S", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersImportsClause1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports $$"), "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersImportsClause2() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", "Imports System, $$"), "System") Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "Imports System, $$"), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes1() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", CreateContent("<$$>")), "System") Await VerifyItemExistsAsync(AddImportsStatement("Imports System", CreateContent("<$$>")), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes2() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("<$$>", "Class Cl")), "System") Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("<$$>", "Class Cl")), "String") End Function <WorkItem(529191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529191")> <WpfFact(Skip:="529191"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributes3() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class Cl", " <$$>", " Function Method()")), "System") Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class Cl", " <$$>", " Function Method()")), "String") End Function #End Region #End Region #Region "SymbolCompletionProviderTests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function IsCommitCharacterTest() As Task Const code = " Imports System Class C Sub M() $$ End Sub End Class" Await VerifyCommonCommitCharactersAsync(code, textTypedSoFar:="") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Sub IsTextualTriggerCharacterTest() TestCommonIsTextualTriggerCharacter() End Sub <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SendEnterThroughToEditorTest() As Task Const code = " Imports System Class C Sub M() $$ End Sub End Class" Await VerifySendEnterThroughToEditorAsync(code, "Int32", expected:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterDateLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call #1/1/2010#.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterStringLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call """".$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterTrueLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call True.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterFalseLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call False.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterNumericLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call 2.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterCharacterLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call ""c""c.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersAfterNothingLiteral() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod("Call Nothing.$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedDateLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (#1/1/2010#).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedStringLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call ("""").$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedTrueLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (True).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedFalseLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (False).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedNumericLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (2).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMembersAfterParenthesizedCharacterLiteral() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (""c""c).$$")), "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersAfterParenthesizedNothingLiteral() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", AddInsideMethod("Call (Nothing).$$")), "Equals") End Function <WorkItem(539243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539243")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedClassesInImports() As Task Await VerifyItemExistsAsync("Imports System.$$", "Console") End Function <WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceTypesAvailableInImportsAlias() As Task Await VerifyItemExistsAsync("Imports S = System.$$", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceTypesAvailableInImports() As Task Await VerifyItemExistsAsync("Imports System.$$", "String") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVarInMethod() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", AddInsideMethod("Dim banana As Integer = 4" + vbCrLf + "$$")), "banana") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestCommandCompletionsInScript() As Task Await VerifyItemExistsAsync(<text>#$$</text>.Value, "#R", sourceCodeKind:=SourceCodeKind.Script) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReferenceCompletionsInScript() As Task Await VerifyItemExistsAsync(<text>#r "$$"</text>.Value, "System.dll", sourceCodeKind:=SourceCodeKind.Script) End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "s") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "Method") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "field") End Function <WorkItem(539300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539300")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() Me.$$ End Sub Shared Sub Method() End Sub End Class </Text>.Value, "M") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMe() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Event X() Sub Test() Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMyClass() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Shared Event X() Sub Test() MyClass.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterMyBase() As Task Await VerifyItemIsAbsentAsync( <Text> Class C1 Public Event E(x As Integer) End Class Class C2 Inherits C1 Sub M1() MyBase.$$ End Sub End Class </Text>.Value, "E") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoEventSymbolAfterInstanceMember() As Task Await VerifyItemIsAbsentAsync( <Text> Class EventClass Public Shared Event X() Sub Test() Dim a As New EventClass() a.$$ End Sub End Class </Text>.Value, "E") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterMeInAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() AddHandler Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterInstanceMemberInAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() AddHandler a.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterInstanceMemberInParenthesizedAddHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() AddHandler (a.$$), a.XEvent End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEventSymbolAfterMeInRemoveHandlerContext() As Task Await VerifyItemExistsAsync( <Text> Class EventClass Public Event X() Sub Test() RemoveHandler Me.$$ End Sub End Class </Text>.Value, "X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoImplicitlyDeclaredMembersFromEventDeclarationAfterMe() As Task Dim source = <Text> Class EventClass Public Event X() Sub Test() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "XEventHandler") Await VerifyItemIsAbsentAsync(source, "XEvent") Await VerifyItemIsAbsentAsync(source, "add_X") Await VerifyItemIsAbsentAsync(source, "remove_X") End Function <WorkItem(530617, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530617")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoImplicitlyDeclaredMembersFromEventDeclarationAfterInstance() As Task Dim source = <Text> Class EventClass Public Event X() Sub Test() Dim a As New EventClass() a.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "XEventHandler") Await VerifyItemIsAbsentAsync(source, "XEvent") Await VerifyItemIsAbsentAsync(source, "add_X") Await VerifyItemIsAbsentAsync(source, "remove_X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredEventHandler() As Task Dim source = <Text> Class EventClass Public Event X() Dim a As $$ End Class </Text>.Value Await VerifyItemExistsAsync(source, "XEventHandler") End Function <WorkItem(529570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529570")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredFieldFromWithEvents() As Task Dim source = <Text> Public Class C1 Protected WithEvents w As C1 = Me Sub Goo() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "_w") End Function <WorkItem(529147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529147")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplicitlyDeclaredFieldFromAutoProperty() As Task Dim source = <Text> Class C1 Property X As C1 Sub test() Me.$$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(source, "_X") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingBeforeDot() As Task Dim code = <Text> Module Module1 Sub Main() .$$ End Sub End Module </Text>.Value Await VerifyItemIsAbsentAsync(code, "Main") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterWithMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "s") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersAfterWithMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "Method") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterWithMe1() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "field") End Function <WorkItem(539276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539276")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersAfterWithMe2() As Task Await VerifyItemExistsAsync( <Text> Class C Dim field As Integer Shared s As Integer Sub M() With Me .$$ End With End Sub Shared Sub Method() End Sub End Class </Text>.Value, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNestedWithBlocks() As Task Await VerifyItemExistsAsync( <Text> Class C Sub M() Dim s As String = "" With s With .Length .$$ End With End With End Sub End Class </Text>.Value, "ToString") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembers() As Task Await VerifyItemExistsAsync( <Text> $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersAfterStatement() As Task Await VerifyItemExistsAsync( <Text> Dim x = 1: $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) Await VerifyItemExistsAsync( <Text> Dim x = 1 $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) Await VerifyItemIsAbsentAsync( <Text> Dim x = 1 $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalStatementMembersBeforeDirectives() As Task Await VerifyItemIsAbsentAsync( <Text> $$ #If DEBUG #End If </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersInsideDirectives() As Task Await VerifyItemIsAbsentAsync( <Text> #If $$ </Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestGlobalScriptMembersAfterAnnotation() As Task Await VerifyItemIsAbsentAsync( <Text><![CDATA[ <Annotation> $$ ]]></Text>.Value, "Console", sourceCodeKind:=SourceCodeKind.Script) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoSharedMembers() As Task Dim test = <Text> Class C Sub M() Dim s = 1 s.$$ End Sub End Class </Text>.Value ' This is an intentional change from Dev12 behavior where constant ' field members were shown Await VerifyItemIsAbsentAsync(test, "MaxValue") Await VerifyItemIsAbsentAsync(test, "ReferenceEquals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelAfterGoto1() As Task Dim test = <Text> Class C Sub M() Goo: Dim i As Integer Goto $$" </Text>.Value Await VerifyItemExistsAsync(test, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelAfterGoto2() As Task Dim test = <Text> Class C Sub M() Goo: Dim i As Integer Goto Goo $$" </Text>.Value Await VerifyItemIsAbsentAsync(test, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LabelAfterGoto3() As Task Dim test = <Text> Class C Sub M() 10: Dim i As Integer Goto $$" </Text>.Value.NormalizeLineEndings() Dim text As String = Nothing Dim position As Integer MarkupTestFile.GetPosition(test, text, position) ' We don't trigger intellisense within numeric literals, so we ' explicitly test only the "nothing typed" case. ' This is also the Dev12 behavior for suggesting labels. Await VerifyAtPositionAsync( text, position, usePreviousCharAsTrigger:=True, expectedItemOrNull:="10", expectedDescriptionOrNull:=Nothing, sourceCodeKind:=SourceCodeKind.Regular, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, matchingFilters:=Nothing) End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias1() As Task Dim test = <Text> Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M N.$$ End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "A") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias2() As Task Dim test = <Text> Imports N = NS1.NS2 Namespace NS1.NS2 Public Class A Public Shared Sub M N.A.$$ End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "M") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias3() As Task Dim test = <Text> Imports System Imports System.Collections.Generic Imports System.Linq Imports N = NS1.NS2 Module Program Sub Main(args As String()) N.$$ End Sub End Module Namespace NS1.NS2 Public Class A Public Shared Sub M End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "A") End Function <WorkItem(541235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541235")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAlias4() As Task Dim test = <Text> Imports System Imports System.Collections.Generic Imports System.Linq Imports N = NS1.NS2 Module Program Sub Main(args As String()) N.A.$$ End Sub End Module Namespace NS1.NS2 Public Class A Public Shared Sub M End Sub End Class End Namespace </Text>.Value Await VerifyItemExistsAsync(test, "M") End Function <WorkItem(541399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541399")> <WorkItem(529190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529190")> <WpfFact(Skip:="529190"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterSingleLineIf() As Task Dim test = <Text> Module Program Sub Main(args As String()) Dim x1 As Integer If True Then $$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(test, "x1") End Function <WorkItem(540442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540442")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyInterfacesInImplementsStatements() As Task Dim test = <Text> Interface IOuter Delegate Sub Del() Interface INested Sub DoNested() End Interface End Interface Class nested Implements IOuter.$$ </Text> Await VerifyItemExistsAsync(test.Value, "INested") Await VerifyItemIsAbsentAsync(test.Value, "Del") End Function <WorkItem(540442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540442")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNestedInterfaceInImplementsClause() As Task Dim test = <Text> Interface IOuter Sub DoOuter() Interface INested Sub DoNested() End Interface End Interface Class nested Implements IOuter.INested Sub DoStuff() implements IOuter.$$ </Text> Await VerifyItemExistsAsync(test.Value, "INested") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingAfterBadQualifiedImplementsClause() As Task Dim test = <Text> Class SomeClass Implements Gibberish.$$ End Class </Text> Await VerifyNoItemsExistAsync(test.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingAfterBadImplementsClause() As Task Dim test = <Text> Module Module1 Sub Goo() End Sub End Module Class SomeClass Sub DoStuff() Implements Module1.$$ </Text> Await VerifyItemIsAbsentAsync(test.Value, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescriptionGenericTypeParameter() As Task Dim test = <Text><![CDATA[ Class SomeClass(Of T) Sub M() $$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "T", $"T {FeaturesResources.in_} SomeClass(Of T)") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeName() As Task Dim test = <Text><![CDATA[ Imports System <$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameAfterSpecifier() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeList() As Task Dim test = <Text><![CDATA[ Imports System <CLSCompliant,$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeListAfterSpecifier() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:CLSCompliant,Assembly:$$ ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameBeforeClass() As Task Dim test = <Text><![CDATA[ Imports System <$$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameAfterSpecifierBeforeClass() As Task Dim test = <Text><![CDATA[ Imports System <Assembly:$$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliant") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliantAttribute") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInAttributeArgumentList() As Task Dim test = <Text><![CDATA[ Imports System <CLSCompliant($$ Public Class C End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliantAttribute") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliant") End Function <WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeNameInsideClass() As Task Dim test = <Text><![CDATA[ Imports System Public Class C Dim c As $$ End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "CLSCompliantAttribute") Await VerifyItemIsAbsentAsync(test.Value, "CLSCompliant") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewAfterMeWhenFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Me.$$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMeWhenNotFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Dim x As Integer Me.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMeWhenFirstStatementInSingleCtor() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNewAfterMyClassWhenFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemExistsAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMyClassWhenNotFirstStatementInCtor() As Task Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) Me.New(accountKey, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) Me.New(accountKey, accountName, Nothing) End Sub Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) Dim x As Integer MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542441")> <WorkItem(759729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/759729")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNewAfterMyClassWhenFirstStatementInSingleCtor() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim test = <Text><![CDATA[ Class C1 Public Sub New(ByVal accountKey As Integer) MyClass.$$ End Sub End Class ]]></Text> Await VerifyItemIsAbsentAsync(test.Value, "New") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext1() As Task ' This is different from Dev10, where we lead users to call the same .ctor, which is illegal. Dim markup = <Text><![CDATA[ Imports System <$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Bar") Await VerifyItemIsAbsentAsync(markup, "D") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext2() As Task Dim markup = <Text><![CDATA[ Imports System <Bar.$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") Await VerifyItemIsAbsentAsync(markup, "C1") End Function <WorkItem(542242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542242")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyShowAttributesInAttributeNameContext3() As Task Dim markup = <Text><![CDATA[ Imports System <Bar.Goo.$$ Class C End Class Class D End Class Class Bar MustInherit Class Goo Class SomethingAttribute Inherits Attribute End Class Class C2 End Class End Class Class C1 End Class End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Something") Await VerifyItemIsAbsentAsync(markup, "C2") End Function <WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute1() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute2() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.$$> ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Namespace2") Await VerifyItemExistsAsync(markup, "Namespace3") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute3() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.Namespace3.$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace4") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute4() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <Namespace1.Namespace3.Namespace4.$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Custom") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() As Task Dim markup = <Text><![CDATA[ Imports Namespace1Alias = Namespace1 Imports Namespace2Alias = Namespace1.Namespace2 Imports Namespace3Alias = Namespace1.Namespace3 Imports Namespace4Alias = Namespace1.Namespace3.Namespace4 Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class CustomAttribute Inherits System.Attribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Namespace1Alias") Await VerifyItemIsAbsentAsync(markup, "Namespace2Alias") Await VerifyItemExistsAsync(markup, "Namespace3Alias") Await VerifyItemExistsAsync(markup, "Namespace4Alias") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AttributeSearch_NamespaceWithoutNestedAttribute() As Task Dim markup = <Text><![CDATA[ Namespace Namespace1 Namespace Namespace2 Class NonAttribute End Class End Namespace Namespace Namespace3.Namespace4 Class NonAttribute Inherits System.NonAttribute End Class End Namespace End Namespace <$$> ]]></Text>.Value Await VerifyItemIsAbsentAsync(markup, "Namespace1") End Function <WorkItem(542737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542737")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestQueryVariableAfterSelectClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From num In Enumerable.Range(3, 4) Select $$ ]]></Text>.Value Await VerifyItemExistsAsync(markup, "num") End Function <WorkItem(542683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542683")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplementsClassesWithNestedInterfaces() As Task Dim markup = <Text><![CDATA[ Interface MyInterface1 Class MyClass2 Interface MyInterface3 End Interface End Class Class MyClass3 End Class End Interface Class D Implements MyInterface1.$$ End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "MyClass2") Await VerifyItemIsAbsentAsync(markup, "MyClass3") End Function <WorkItem(542683, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542683")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplementsClassesWithNestedInterfacesClassOutermost() As Task Dim markup = <Text><![CDATA[ Class MyClass1 Class MyClass2 Interface MyInterface End Interface End Class End Class Class G Implements $$ End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "MyClass1") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select i,$$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542876, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542876")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQuerySelect3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = From i In New Integer() {1}, j In New String() {""} Select i, $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i") Await VerifyItemExistsAsync(markup, "j") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim arr = New Integer() {1} Dim query = From i In arr Group By i Into $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Count") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into Group, $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542927, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542927")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryGroupByInto4() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.CompilerServices Module Program Sub Main() Dim col = New String() { } Dim temp = From x in col Group By x.Length Into g = $$ End Sub <Extension()> Function LongestString(list As IEnumerable(Of String)) As String Return list.First() End Function End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "LongestString") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto1() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Distinct") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto2() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Distinct") End Function <WorkItem(542929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542929")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInQueryAggregateInto3() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main() Dim query = Aggregate i In New Integer() {1} Into d = Distinct(), $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Sum") End Function <WorkItem(543137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543137")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAndKeywordInComplexJoin() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Module1 Sub Main(args As String()) Dim arr = New Byte() {4, 5} Dim q2 = From num In arr Join n1 In arr On num.ToString() Equals n1.ToString() And $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "num") End Function <WorkItem(543181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543181")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterGroupKeywordInGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From i1 In New Integer() {4, 5} Group $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") End Function <WorkItem(543182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543182")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterByInGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim q1 = From i1 In New Integer() {3, 2} Group i1 By $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") End Function <WorkItem(543210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543210")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterByInsideExprVarDeclGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q1 = From i1 In arr Group i1 By i2 = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") Await VerifyItemExistsAsync(markup, "arr") Await VerifyItemExistsAsync(markup, "args") End Function <WorkItem(543213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterGroupInsideExprVarDeclGroupByClause() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q1 = From i1 In arr Group i1 = $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "i1") Await VerifyItemExistsAsync(markup, "arr") Await VerifyItemExistsAsync(markup, "args") End Function <WorkItem(543246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543246")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAggregateKeyword() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Linq Module Program Sub Main(args As String()) Dim query = Aggregate $$ ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDelegateCreationExpression1() As Task Dim markup = <Text> Module Program Sub Main(args As String()) Dim f1 As New Goo2($$ End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </Text>.Value Await VerifyItemIsAbsentAsync(markup, "Goo2") Await VerifyItemIsAbsentAsync(markup, "Bar2") End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterDelegateCreationExpression2() As Task Dim markup = <Text> Module Program Sub Main(args As String()) Dim f1 = New Goo2($$ End Sub Delegate Sub Goo2() Function Bar2() As Object Return Nothing End Function End Module </Text>.Value Await VerifyItemIsAbsentAsync(markup, "Goo2") Await VerifyItemIsAbsentAsync(markup, "Bar2") End Function <WorkItem(619388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619388")> <WpfFact(Skip:="619388"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverloadsHiding() As Task Dim markup = <Text><![CDATA[ Public Class Base Sub Configure() End Sub End Class Public Class Derived Inherits Base Overloads Sub Configure() Config$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Configure", "Sub Derived.Configure()") Await VerifyItemIsAbsentAsync(markup, "Configure", "Sub Base.Configure()") End Function <WorkItem(543580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543580")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterMyBaseDot1() As Task Dim markup = <Text><![CDATA[ Public Class Base Protected Sub Configure() Console.WriteLine("test") End Sub End Class Public Class Inherited Inherits Base Public Shadows Sub Configure() MyBase.$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Configure") End Function <WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNothingMyBaseDotInScriptContext() As Task Await VerifyItemIsAbsentAsync("MyBase.$$", "ToString", sourceCodeKind:=SourceCodeKind.Script) End Function <WorkItem(543580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543580")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterMyBaseDot2() As Task Dim markup = <Text> Public Class Base Protected Sub Goo() Console.WriteLine("test") End Sub End Class Public Class Inherited Inherits Base Public Sub Bar() MyBase.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "Goo") Await VerifyItemIsAbsentAsync(markup, "Bar") End Function <WorkItem(543547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543547")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterRaiseEvent() As Task Dim markup = <Text> Module Program Public Event NewRegistrations(ByVal pStudents As String) Sub Main(args As String()) RaiseEvent $$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "NewRegistrations") End Function <WorkItem(543730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543730")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInheritedEventsAfterRaiseEvent() As Task Dim markup = <Text> Class C1 Event baseEvent End Class Class C2 Inherits C1 Event derivedEvent(x As Integer) Sub M() RaiseEvent $$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "derivedEvent") Await VerifyItemIsAbsentAsync(markup, "baseEvent") End Function <WorkItem(529116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529116")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInSingleLineLambda1() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x5 = Function(x1) $$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "x1") Await VerifyItemExistsAsync(markup, "x5") End Function <WorkItem(529116, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529116")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInSingleLineLambda2() As Task Dim markup = <Text><![CDATA[ Module Program Sub Main(args As String()) Dim x5 = Function(x1)$$ End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "x1") Await VerifyItemExistsAsync(markup, "x5") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <WorkItem(530595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530595")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsInSharedMethod() As Task Dim markup = <Text> Class C Private x As Integer Shared Sub M() $$ End Sub End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsInSharedFieldInitializer() As Task Dim markup = <Text> Class C Private x As Integer Private Shared y As Integer = $$ End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsInSharedMethod() As Task Dim markup = <Text> Class C Private Shared x As Integer Shared Sub M() $$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "x") End Function <WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsInSharedFieldInitializer() As Task Dim markup = <Text> Class C Private Shared x As Integer Private Shared y As Integer = $$ End Class </Text>.Value Await VerifyItemExistsAsync(markup, "x") End Function <WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceFieldsFromOuterClassInInstanceMethod() As Task Dim markup = <Text> Class outer Dim i As Integer Class inner Sub M() $$ End Sub End Class End Class </Text>.Value Await VerifyItemIsAbsentAsync(markup, "i") End Function <WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedFieldsFromOuterClassInInstanceMethod() As Task Dim markup = <Text> Class outer Shared i As Integer Class inner Sub M() $$ End Sub End Class End Class </Text>.Value Await VerifyItemExistsAsync(markup, "i") End Function <WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOnlyEnumMembersInEnumTypeMemberAccess() As Task Dim markup = <Text> Class C Enum x a b c End Enum Sub M() x.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "a") Await VerifyItemExistsAsync(markup, "b") Await VerifyItemExistsAsync(markup, "c") Await VerifyItemIsAbsentAsync(markup, "Equals") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping1() As Task Dim markup = <Text> Module [Structure] Sub M() dim [dim] = 0 console.writeline($$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "dim") Await VerifyItemIsAbsentAsync(markup, "[dim]") Await VerifyItemExistsAsync(markup, "Structure") Await VerifyItemIsAbsentAsync(markup, "[Structure]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping2() As Task Dim markup = <Text> Module [Structure] Sub [dim]() End Sub Sub [New]() End Sub Sub [rem]() [Structure].$$ End Sub End Module </Text>.Value Await VerifyItemExistsAsync(markup, "dim") Await VerifyItemIsAbsentAsync(markup, "[dim]") Await VerifyItemExistsAsync(markup, "New") Await VerifyItemIsAbsentAsync(markup, "[New]") Await VerifyItemExistsAsync(markup, "rem") Await VerifyItemIsAbsentAsync(markup, "[rem]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestKeywordEscaping3() As Task Dim markup = <Text> Namespace Goo Module [Structure] Sub M() Dim x as Goo.$$ End Sub End Module End Namespace </Text>.Value Await VerifyItemExistsAsync(markup, "Structure") Await VerifyItemIsAbsentAsync(markup, "[Structure]") End Function <WorkItem(539450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539450")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributeKeywordEscaping() As Task Dim markup = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;$$ Class C End Class </Text>.Value Await VerifyItemExistsAsync(markup, "class") Await VerifyItemIsAbsentAsync(markup, "[class]") End Function <WorkItem(645898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645898")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EscapedKeywordAttributeCommit() As Task Dim markup = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;$$ Class C End Class </Text>.Value Dim expected = <Text> Imports System Class classattribute : Inherits Attribute End Class &lt;[class]( Class C End Class </Text>.Value Await VerifyProviderCommitAsync(markup, "class", expected, "("c) End Function <WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllMembersInEnumLocalAccess() As Task Dim markup = <Text> Class C Enum x a b c End Enum Sub M() Dim y = x.a y.$$ End Sub End Class </Text>.Value Await VerifyItemExistsAsync(markup, "a") Await VerifyItemExistsAsync(markup, "b") Await VerifyItemExistsAsync(markup, "c") Await VerifyItemExistsAsync(markup, "Equals") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestReadOnlyPropertiesPresentOnRightSideInObjectInitializer() As Task Dim text = <a>Class C Public Property Goo As Integer Public ReadOnly Property Bar As Integer Get Return 0 End Get End Property Sub M() Dim c As New C With { .Goo = .$$ End Sub End Class</a>.Value Await VerifyItemExistsAsync(text, "Goo") Await VerifyItemExistsAsync(text, "Bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeExplicitDeclaration_ExplicitOff() As Task Dim text = <Text> Option Explicit Off Class C Sub M() $$ Dim goo = 3 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeExplicitDeclaration_ExplicitOn() As Task Dim text = <Text> Option Explicit On Class C Sub M() $$ Dim goo = 3 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "goo") End Function <WorkItem(10572, "DevDiv_Projects/Roslyn")> <WorkItem(530595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530595")> <Fact> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableBeforeImplicitDeclaration() As Task Dim text = <Text> Option Explicit Off Class C Function M() as Integer $$ Return goo End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableInItsDeclaration() As Task ' "Dim goo As Integer = goo" is legal code while "Dim goo = goo" is not, but ' offer the local name on the right in either case because in the second ' case there's an error stating that goo needs to be explicitly typed and ' the user can then add the As clause. This mimics the behavior of ' "var x = x = 0" in C#. Dim text = <Text> Class C Sub M() Dim goo = $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableInItsDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = 4, bar = $$, baz = 5 End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableNotBeforeItsDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = $$, bar = 5 End Sub End Class</Text>.Value Await VerifyItemIsAbsentAsync(text, "bar") End Function <Fact> <WorkItem(10572, "DevDiv_Projects/Roslyn")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLocalVariableAfterDeclarator() As Task Dim text = <Text> Class C Sub M() Dim goo = 5, bar = $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(545439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545439")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterReDim() As Task Dim text = <Text> Class C Sub M() Dim goo(10, 20) As Integer ReDim $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(545439, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545439")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestArrayAfterReDimPreserve() As Task Dim text = <Text> Class C Sub M() Dim goo(10, 20) As Integer ReDim Preserve $$ End Sub End Class</Text>.Value Await VerifyItemExistsAsync(text, "goo") End Function <Fact> <WorkItem(546353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546353")> <Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoNamespaceDeclarationIntellisense() As Task Dim text = <Text> Namespace Goo.$$ Class C End Class</Text>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(531258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531258")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLabelsAfterOnErrorGoTo() As Task Dim code = <Code> Class C Sub M() On Error GoTo $$ label1: Dim x = 1 End Sub End Class</Code>.Value Await VerifyItemExistsAsync(code, "label1") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAwaitableItem() As Task Dim code = <Code> Imports System.Threading.Tasks Class C ''' &lt;summary&gt; ''' Doc Comment! ''' &lt;/summary&gt; Async Function Goo() As Task Me.$$ End Function End Class</Code>.Value Dim description = $"<{VBFeaturesResources.Awaitable}> Function C.Goo() As Task Doc Comment!" Await VerifyItemWithMscorlib45Async(code, "Goo", description, LanguageNames.VisualBasic) End Function <WorkItem(550760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550760")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAfterAwait() As Task Dim code = <Code> Imports System.Threading.Tasks Class SomeClass Public Async Sub goo() Await $$ End Sub Async Function Bar() As Task(Of Integer) Return Await Task.Run(Function() 42) End Function End Class</Code>.Value Await VerifyItemExistsAsync(code, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestObsoleteItem() As Task Dim code = <Code> Imports System Class SomeClass &lt;Obsolete&gt; Public Sub Goo() $$ End Sub End Class</Code>.Value Await VerifyItemExistsAsync(code, "Goo", $"({VBFeaturesResources.Deprecated}) Sub SomeClass.Goo()") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExpressionAfterYield() As Task Dim code = <Code> Class SomeClass Iterator Function Goo() As Integer Dim x As Integer Yield $$ End Function End Class </Code>.Value Await VerifyItemExistsAsync(code, "x") End Function <WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoMembersOnDottingIntoUnboundType() As Task Dim code = <Code> Module Program Dim goo As RegistryKey Sub Main(args() As String) goo.$$ End Sub End Module </Code>.Value Await VerifyNoItemsExistAsync(code) End Function <WorkItem(611154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611154")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoOperators() As Task Await VerifyItemIsAbsentAsync( AddInsideMethod("String.$$"), "op_Equality") End Function <WorkItem(736891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736891")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInBinaryConditionalExpression() As Task Dim code = <Code> Module Program Sub Main(args() As String) args = If($$ End Sub End Module </Code>.Value Await VerifyItemExistsAsync(code, "args") End Function <WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInTopLevelFieldInitializer() As Task Dim code = <Code> Dim aaa = 1 Dim bbb = $$ </Code>.Value Await VerifyItemExistsAsync(code, "aaa") End Function #End Region #Region "SharedMemberSourceTests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation1() As Task Await VerifyItemIsAbsentAsync("System.Console.$$", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation2() As Task Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", "System.Console.$$"), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation3() As Task Await VerifyItemIsAbsentAsync("Imports System.Console.$$", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation4() As Task Await VerifyItemIsAbsentAsync( AddImportsStatement("Imports System", CreateContent("Class C ", "' Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation5() As Task Await VerifyItemIsAbsentAsync(AddImportsStatement("Imports System", AddInsideMethod("Dim d = ""Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInvalidLocation6() As Task Await VerifyItemIsAbsentAsync("<System.Console.$$>", "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInsideMethodBody() As Task Await VerifyItemExistsAsync(AddImportsStatement("Imports System", AddInsideMethod("Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInsideAccessorBody() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", " Property Prop As String", " Get", " Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestFieldInitializer() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", " Dim d = Console.$$")), "Beep") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMethods() As Task Await VerifyItemExistsAsync( AddImportsStatement("Imports System", CreateContent("Class C ", "Private Shared Function Method() As Boolean", "End Function", " Dim d = $$", "")), "Method") End Function #End Region #Region "EditorBrowsableTests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Shared Sub Bar() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar(x as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Method_Overloads_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Shared Sub Bar(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestOverriddenSymbolsFilteredFromCompletionList() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d as D d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class B Public Overridable Sub Goo(original As Integer) End Sub End Class Public Class D Inherits B Public Overrides Sub Goo(derived As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c = New C() c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class C Public Sub Goo() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d = new D() d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class B Public Sub Goo() End Sub End Class Public Class D Inherits B Public Overloads Sub Goo(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_HidingWithDifferentArgumentList() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim d = new D() d.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Class B Public Sub Goo() End Sub End Class Public Class D Inherits B Public Sub Goo(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_BrowsableStateNeverMethodsInBaseClass() As Task Dim markup = <Text><![CDATA[ Class Program Inherits B Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class B <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) Public Sub Goo(t As T) End Sub Public Sub Goo(i as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t as T) End Sub Public Sub Goo(i as Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(i As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim ci = new C(Of Integer)() ci.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(i As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) Public Sub Goo(t As T) End Sub Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=2, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cii = new C(Of Integer, Of Integer)() cii.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C(Of T, U) <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(t As T) End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(u As U) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=2, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Field_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public bar As Integer End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo Public Property Bar As Integer <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Get Return 5 End Get <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Property_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim goo As Goo goo.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Property Bar As Integer Get Return 5 End Get Set(value As Integer) End Set End Property End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Bar", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New() End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_MixedOverloads1() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Constructor_MixedOverloads2() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x = New $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New() End Sub <System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Event_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C AddHandler c.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C Delegate Sub DelegateType() <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Event Handler As DelegateType End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Handler", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Delegate_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Event e As $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Delegate Sub DelegateType() ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="DelegateType", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateNever_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAlways_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Inherits $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class Goo End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_BrowsableStateAdvanced_FullyQualified() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As NS.$$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Namespace NS <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C End Class End Namespace ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="C", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Class_IgnoreBaseClassBrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class Goo Inherits Bar End Class <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Bar End Class ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Structure Goo End Structure ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateNever() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateAlways() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Enum_BrowsableStateAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Enum Goo A End Enum ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() As Task Dim markup = <Text><![CDATA[ Class Program Public Sub M() $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() As Task Dim markup = <Text><![CDATA[ Class Program Implements $$ End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Interface Goo End Interface ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_CrossLanguage_VBtoCS_Always() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x As $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { } ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=1, expectedSymbolsMetadataReference:=1, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.CSharp, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestEditorBrowsable_CrossLanguage_VBtoCS_Never() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim x As $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { } ]]></Text>.Value Await VerifyItemInEditorBrowsableContextsAsync( markup:=markup, referencedCode:=referencedCode, item:="Goo", expectedSymbolsSameSolution:=0, expectedSymbolsMetadataReference:=0, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.CSharp, hideAdvancedMembers:=False) End Function #End Region #Region "Inherits/Implements Tests" <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInherits() As Task Const markup = " Public Class Base End Class Class Derived Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "Base") Await VerifyItemIsAbsentAsync(markup, "Derived") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInheritsDotIntoClass() As Task Const markup = " Public Class Base Public Class Nest End Class End Class Class Derived Inherits Base.$$ End Class " Await VerifyItemExistsAsync(markup, "Nest") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplements() As Task Const markup = " Public Interface IGoo End Interface Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IGoo") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AliasedInterfaceAfterImplements() As Task Const markup = " Imports IAlias = IGoo Public Interface IGoo End Interface Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IAlias") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AliasedNamespaceAfterImplements() As Task Const markup = " Imports AliasedNS = NS1 Namespace NS1 Public Interface IGoo End Interface Class C Implements $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedNS") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedClassAfterInherits() As Task Const markup = " Imports AliasedClass = Base Public Class Base End Interface Class C Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "AliasedClass") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedNamespaceAfterInherits() As Task Const markup = " Imports AliasedNS = NS1 Namespace NS1 Public Class Base End Interface Class C Inherits $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedNS") End Function <WorkItem(995986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995986")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AliasedClassAfterInherits2() As Task Const markup = " Imports AliasedClass = NS1.Base Namespace NS1 Public Class Base End Interface Class C Inherits $$ End Class End Namespace " Await VerifyItemExistsAsync(markup, "AliasedClass") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplementsComma() As Task Const markup = " Public Interface IGoo End Interface Public Interface IBar End interface Class C Implements IGoo, $$ End Class " Await VerifyItemExistsAsync(markup, "IBar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_ClassContainingInterface() As Task Const markup = " Public Class Base Public Interface Nest End Class End Class Class Derived Implements $$ End Class " Await VerifyItemExistsAsync(markup, "Base") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_NoClassNotContainingInterface() As Task Const markup = " Public Class Base End Class Class Derived Implements $$ End Class " Await VerifyItemIsAbsentAsync(markup, "Base") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_GenericClass() As Task Const markup = " Public Class base(Of T) End Class Public Class derived Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "base", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_GenericInterface() As Task Const markup = " Public Interface IGoo(Of T) End Interface Public Class bar Implements $$ End Class " Await VerifyItemExistsAsync(markup, "IGoo", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(546610, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546610")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_IncompleteClassDeclaration() As Task Const markup = " Public Interface IGoo End Interface Public Interface IBar End interface Class C Implements IGoo,$$ " Await VerifyItemExistsAsync(markup, "IBar") End Function <WorkItem(546611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546611")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_NotNotInheritable() As Task Const markup = " Public NotInheritable Class D End Class Class C Inherits $$ " Await VerifyItemIsAbsentAsync(markup, "D") End Function <WorkItem(546802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546802")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_KeywordIdentifiersShownUnescaped() As Task Const markup = " Public Class [Inherits] End Class Class C Inherits $$ " Await VerifyItemExistsAsync(markup, "Inherits") End Function <WorkItem(546802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546802")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_KeywordIdentifiersCommitEscaped() As Task Const markup = " Public Class [Inherits] End Class Class C Inherits $$ " Const expected = " Public Class [Inherits] End Class Class C Inherits [Inherits]. " Await VerifyProviderCommitAsync(markup, "Inherits", expected, "."c) End Function <WorkItem(546801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546801")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_Modules() As Task Const markup = " Module Module1 Sub Main() End Sub End Module Module Module2 Class Bx End Class End Module Class Max Class Bx End Class End Class Class A Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "Module2") Await VerifyItemIsAbsentAsync(markup, "Module1") End Function <WorkItem(530726, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530726")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_DoNotShowNamespaceWithNoApplicableClasses() As Task Const markup = " Namespace N Module M End Module End Namespace Class C Inherits $$ End Class " Await VerifyItemIsAbsentAsync(markup, "N") End Function <WorkItem(530725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530725")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_CheckStructContents() As Task Const markup = " Namespace N Public Structure S1 Public Class B End Class End Structure Public Structure S2 End Structure End Namespace Class C Inherits N.$$ End Class " Await VerifyItemIsAbsentAsync(markup, "S2") Await VerifyItemExistsAsync(markup, "S1") End Function <WorkItem(530724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530724")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_NamespaceContainingInterface() As Task Const markup = " Namespace N Interface IGoo End Interface End Namespace Class C Implements $$ End Class " Await VerifyItemExistsAsync(markup, "N") End Function <WorkItem(531256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531256")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_OnlyInterfacesForInterfaceInherits1() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface IGoo Inherits $$ " Await VerifyItemExistsAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(1036374, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036374")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_InterfaceCircularInheritance() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface A(Of T) Inherits A(Of A(Of T)) Interface B Inherits $$ End Interface End Interface " Await VerifyItemExistsAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(531256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531256")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_OnlyInterfacesForInterfaceInherits2() As Task Const markup = " Interface ITestInterface End Interface Class TestClass End Class Interface IGoo Implements $$ " Await VerifyItemIsAbsentAsync(markup, "ITestInterface") Await VerifyItemIsAbsentAsync(markup, "TestClass") End Function <WorkItem(547291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547291")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_CommitGenericOnParen() As Task Const markup = " Class G(Of T) End Class Class DG Inherits $$ End Class " Dim expected = " Class G(Of T) End Class Class DG Inherits G( End Class " Await VerifyProviderCommitAsync(markup, "G(Of " & s_unicodeEllipsis & ")", expected, "("c) End Function <WorkItem(579186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579186")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestImplements_AfterImplementsWithCircularInheritance() As Task Const markup = " Interface I(Of T) End Interface Class C(Of T) Class D Inherits C(Of D) Implements $$ End Class End Class " Await VerifyItemExistsAsync(markup, "I", displayTextSuffix:="(Of …)") End Function <WorkItem(622563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622563")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function Inherits_CommitNonGenericOnParen() As Task Const markup = " Class G End Class Class DG Inherits $$ End Class " Dim expected = " Class G End Class Class DG Inherits G( End Class " Await VerifyProviderCommitAsync(markup, "G", expected, "("c) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_AfterInheritsWithCircularInheritance() As Task Const markup = " Class B End Class Class C(Of T) Class D Inherits C(Of D) Inherits $$ End Class End Class " Await VerifyItemExistsAsync(markup, "B") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_ClassesInsideSealedClasses() As Task Const markup = " Public NotInheritable Class G Public Class H End Class End Class Class SomeClass Inherits $$ End Class " Await VerifyItemExistsAsync(markup, "G") End Function <WorkItem(638762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638762")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInherits_ClassWithinNestedStructs() As Task Const markup = " Structure somestruct Structure Inner Class FinallyAClass End Class End Structure End Structure Class SomeClass Inherits $$ End " Await VerifyItemExistsAsync(markup, "somestruct") End Function #End Region <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExtensionMethodsOffered() As Task Dim markup = <Text><![CDATA[ Imports System.Runtime.CompilerServices Class Program Sub Main(args As String()) Me.$$ End Sub End Class Module Extensions <Extension> Sub Goo(program As Program) End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") End Function <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExtensionMethodsOffered2() As Task Dim markup = <Text><![CDATA[ Imports System.Runtime.CompilerServices Class Program Sub Main(args As String()) Dim a = new Program() a.$$ End Sub End Class Module Extensions <Extension> Sub Goo(program As Program) End Sub End Module ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Goo") End Function <WorkItem(715146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715146")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestLinqExtensionMethodsOffered() As Task Dim markup = <Text><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Linq Class Program Sub Main(args As String()) Dim a as IEnumerable(Of Integer) = Nothing a.$$ End Sub End Class ]]></Text>.Value Await VerifyItemExistsAsync(markup, "Average") End Function <WorkItem(884060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/884060")> <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionOffTypeParameter() As Task Dim markup = <Text><![CDATA[ Module Program Function bar(Of T As Object)() As T T.$$ End Function End Moduleb End Class ]]></Text>.Value Await VerifyNoItemsExistAsync(markup) End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAvailableInBothLinkedFiles() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C Dim x as integer sub goo() $$ end sub end class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences=" True" AssemblyName="Proj2"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) C.x As Integer") End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAvailableInOneLinkedFile() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="GOO=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #If GOO Then Dim x as integer #End If Sub goo() $$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"({FeaturesResources.field}) C.x As Integer" + vbCrLf + vbCrLf + String.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available) + vbCrLf + String.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available) + vbCrLf + vbCrLf + FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <WorkItem(13161, "https://github.com/dotnet/roslyn/issues/13161")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitGenericOnTab() As Task Dim text = <code> Class G(Of T) End Class Class DG Function Bar() as $$ End Class</code>.Value Dim expected = <code> Class G(Of T) End Class Class DG Function Bar() as G(Of End Class</code>.Value Await VerifyProviderCommitAsync(text, "G(Of …)", expected, Nothing) End Function <WorkItem(909121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/909121")> <WorkItem(2048, "https://github.com/dotnet/roslyn/issues/2048")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitGenericOnParen() As Task Dim text = <code> Class G(Of T) End Class Class DG Function Bar() as $$ End Class</code>.Value Dim expected = <code> Class G(Of T) End Class Class DG Function Bar() as G( End Class</code>.Value Await VerifyProviderCommitAsync(text, "G(Of …)", expected, "("c) End Function <WorkItem(668159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/668159")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAttributesShownWithBraceCompletionActive() As Task Dim text = <code><![CDATA[ Imports System <$$> Class C End Class Class GooAttribute Inherits Attribute End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDescriptionInAliasedType() As Task Dim text = <code><![CDATA[ Imports IAlias = IGoo Class C Dim x as IA$$ End Class ''' <summary> ''' summary for interface IGoo ''' </summary> Interface IGoo Sub Bar() End Interface ]]></code>.Value Await VerifyItemExistsAsync(text, "IAlias", expectedDescriptionOrNull:="Interface IGoo" + vbCrLf + "summary for interface IGoo") End Function <WorkItem(842049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842049")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMergedNamespace1() As Task Dim text = <code><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class D End Class End Namespace Module M Dim c As X.C Dim d As X.D Dim e As X.$$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "C") Await VerifyItemExistsAsync(text, "D") End Function <WorkItem(842049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842049")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestMergedNamespace2() As Task Dim text = <code><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class D End Class End Namespace Module M Dim c As X.C Dim d As X.D Sub Goo() X.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "C") Await VerifyItemExistsAsync(text, "D") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_EmptyNameSpan_TopLevel() As Task Dim source = <code><![CDATA[ Namespace $$ End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_EmptyNameSpan_Nested() As Task Dim source = <code><![CDATA[ Namespace System Namespace $$ End Namespace End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_TopLevelNoPeers() As Task Dim source = <code><![CDATA[ Imports System; Namespace $$ ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "String") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_TopLevelWithPeer() As Task Dim source = <code><![CDATA[ Namespace A End Namespace Namespace $$ ]]></code>.Value Await VerifyItemExistsAsync(source, "A") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_NestedWithNoPeers() As Task Dim source = <code><![CDATA[ Namespace A Namespace $$ End Namespace ]]></code>.Value Await VerifyNoItemsExistAsync(source) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_NestedWithPeer() As Task Dim source = <code><![CDATA[ Namespace A Namespace B End Namespace Namespace $$ End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_ExcludesCurrentDeclaration() As Task Dim source = <code><![CDATA[Namespace N$$S]]></code>.Value Await VerifyItemIsAbsentAsync(source, "NS") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_WithNested() As Task Dim source = <code><![CDATA[ Namespace A Namespace $$ Namespace B End Namespace End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_WithNestedAndMatchingPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A Namespace $$ Namespace B End Namespace End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_InnerCompletionPosition() As Task Dim source = <code><![CDATA[ Namespace Sys$$tem End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Unqualified_IncompleteDeclaration() As Task Dim source = <code><![CDATA[ Namespace A Namespace B Namespace $$ Namespace C1 End Namespace End Namespace Namespace B.C2 End Namespace End Namespace Namespace A.B.C3 End Namespace ]]></code>.Value ' Ideally, all the C* namespaces would be recommended but, because of how the parser ' recovers from the missing end statement, they end up with the following qualified names... ' ' C1 => A.B.?.C1 ' C2 => A.B.B.C2 ' C3 => A.A.B.C3 ' ' ...none of which are found by the current algorithm. Await VerifyItemIsAbsentAsync(source, "C1") Await VerifyItemIsAbsentAsync(source, "C2") Await VerifyItemIsAbsentAsync(source, "C3") Await VerifyItemIsAbsentAsync(source, "A") ' Because of the above, B does end up in the completion list ' since A.B.B appears to be a peer of the New declaration Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_NoPeers() As Task Dim source = <code><![CDATA[Namespace A.$$]]></code>.Value Await VerifyNoItemsExistAsync(source) End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_TopLevelWithPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A.$$ ]]></code>.Value Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_NestedWithPeer() As Task Dim source = <code><![CDATA[ Namespace A Namespace B.C End Namespace Namespace B.$$ End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") Await VerifyItemExistsAsync(source, "C") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_WithNested() As Task Dim source = <code><![CDATA[ Namespace A.$$ Namespace B End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_WithNestedAndMatchingPeer() As Task Dim source = <code><![CDATA[ Namespace A.B End Namespace Namespace A.$$ Namespace B End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_InnerCompletionPosition() As Task Dim source = <code><![CDATA[ Namespace Sys$$tem.Runtime End Namespace ]]></code>.Value Await VerifyItemExistsAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_Qualified_IncompleteDeclaration() As Task Dim source = <code><![CDATA[ Namespace A Namespace B Namespace C.$$ Namespace C.D1 End Namespace End Namespace Namespace B.C.D2 End Namespace End Namespace Namespace A.B.C.D3 End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "A") Await VerifyItemIsAbsentAsync(source, "B") Await VerifyItemIsAbsentAsync(source, "C") ' Ideally, all the D* namespaces would be recommended but, because of how the parser ' recovers from the end statement, they end up with the following qualified names... ' ' D1 => A.B.C.C.?.D1 ' D2 => A.B.B.C.D2 ' D3 => A.A.B.C.D3 ' ' ...none of which are found by the current algorithm. Await VerifyItemIsAbsentAsync(source, "D1") Await VerifyItemIsAbsentAsync(source, "D2") Await VerifyItemIsAbsentAsync(source, "D3") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_OnKeyword() As Task Dim source = <code><![CDATA[ Name$$space System End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "System") End Function <WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function NamespaceName_OnNestedKeyword() As Task Dim source = <code><![CDATA[ Namespace System Name$$space Runtime End Namespace End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "System") Await VerifyItemIsAbsentAsync(source, "Runtime") End Function <WorkItem(925469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925469")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitWithCloseBracketLeaveOpeningBracket1() As Task Dim text = <code><![CDATA[ Class Await Sub Goo() Dim x = new [Awa$$] End Sub End Class]]></code>.Value Dim expected = <code><![CDATA[ Class Await Sub Goo() Dim x = new [Await] End Sub End Class]]></code>.Value Await VerifyProviderCommitAsync(text, "Await", expected, "]"c) End Function <WorkItem(925469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/925469")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CommitWithCloseBracketLeavesOpeningBracket2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new [Cla$$] End Sub End Class]]></code>.Value Dim expected = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new [Class] End Sub End Class]]></code>.Value Await VerifyProviderCommitAsync(text, "Class", expected, "]"c) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletion() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new Object() x?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletion2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo() Dim x = new Object() x?.ToString()?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletionForNullableParameterSymbols_1() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo(dt As System.DateTime?) dt?.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Day") Await VerifyItemIsAbsentAsync(text, "Value") End Function <WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalOperatorCompletionForNullableParameterSymbols_2() As Task Dim text = <code><![CDATA[ Class [Class] Sub Goo(dt As System.DateTime?) dt.$$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Value") Await VerifyItemIsAbsentAsync(text, "Day") End Function <WorkItem(1041269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041269")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestHidePropertyBackingFieldAndEventsAtExpressionLevel() As Task Dim text = <code><![CDATA[ Imports System Class C Property p As Integer = 15 Event e as EventHandler Sub f() Dim x = $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "_p") Await VerifyItemIsAbsentAsync(text, "e") End Function <WorkItem(1041269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1041269")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableForConditionalAccess() As Task Dim text = <code><![CDATA[ Class C Sub Goo() Dim x as Integer? = Nothing x?.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "GetTypeCode") Await VerifyItemIsAbsentAsync(text, "HasValue") End Function <WorkItem(1079694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDontThrowForNullPropagatingOperatorInErase() As Task Dim text = <code><![CDATA[ Module Program Sub Main() Dim x?(1) Erase x?.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestUnwrapNullableForConditionalFromStructure() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As A x?.$$b?.c End Sub End Module Structure A Public b As B End Structure Public Class B Public c As C End Class Public Class C End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "b") Await VerifyItemIsAbsentAsync(text, "c") End Function <WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestWithinChainOfConditionalAccess() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As A x?.$$b?.c End Sub End Module Class A Public b As B End Class Public Class B Public c As C End Class Public Class C End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "b") Await VerifyItemIsAbsentAsync(text, "c") End Function <WorkItem(1079694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079694")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDontThrowForNullPropagatingOperatorOnTypeParameter() As Task Dim text = <code><![CDATA[ Module Program Sub Goo(Of T)(x As T) x?.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "ToString") End Function <WorkItem(1079723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079723")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionAfterNullPropagatingOperatingInWithBlock() As Task Dim text = <code><![CDATA[ Option Strict On Module Program Sub Main() Dim s = "" With s ?.$$ End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext1() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext2() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext3() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext4() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf($$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext5() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext6() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext7() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext8() As Task Dim text = <code><![CDATA[ Class C Shared Sub M() Dim s = NameOf(C.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext9() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(Me.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext10() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(Me.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext11() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyClass.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext12() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyClass.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext13() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyBase.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext14() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim s = NameOf(MyBase.$$ End Sub Shared Sub Goo() End Sub Sub Bar() End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext15() As Task Dim text = <code><![CDATA[ Class C Shared Sub Goo() End Sub Sub Bar() End Sub End Class Class D Inherits C Sub M() Dim s = NameOf(MyBase.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Goo") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInNameOfArgumentContext16() As Task Dim text = <code><![CDATA[ Class C Shared Sub Goo() End Sub Sub Bar() End Sub End Class Class D Inherits C Sub M() Dim s = NameOf(MyBase.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(46472, "https://github.com/dotnet/roslyn/issues/46472")> Public Async Function TestAllowCompletionInNameOfArgumentContext17() As Task Dim text = <code><![CDATA[ Public Class C Event Bar() Public Sub Baz() Dim s = NameOf($$ End Sub End Class]]></code>.Value Await VerifyItemExistsAsync(text, "Bar") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInInterpolationExpressionContext1() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{$$}" End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestAllowCompletionInInterpolationExpressionContext2() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{$$ ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionInInterpolationAlignmentContext() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{x,$$}" End Sub End Class ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionInInterpolationFormatContext() As Task Dim text = <code><![CDATA[ Class C Sub M() Dim x = 1 Dim s = $"{x:$$}" End Sub End Class ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(1293, "https://github.com/dotnet/roslyn/issues/1293")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestTriggeredAfterDotInWithAfterNumericLiteral() As Task Dim text = <code><![CDATA[ Class Program Public Property P As Long Sub M() With Me .P = 122 .$$ End With End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M", usePreviousCharAsTrigger:=True) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes1() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) System?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes2() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Console?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoCompletionForConditionalAccessOnTypes3() As Task Dim text = <code><![CDATA[ Imports a = System Module Program Sub Main(args As String()) a?.$$ End Sub End Module ]]></code>.Value Await VerifyNoItemsExistAsync(text) End Function <WorkItem(3086, "https://github.com/dotnet/roslyn/issues/3086")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedMembersOffInstanceInColorColor() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x = C.$$ End Sub Dim C As New C() End Module Class C Public X As Integer = 1 Public Shared Y As Integer = 2 End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "X") Await VerifyItemExistsAsync(text, "Y") End Function <WorkItem(3086, "https://github.com/dotnet/roslyn/issues/3086")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNotSharedMembersOffAliasInColorColor() As Task Dim text = <code><![CDATA[ Imports B = C Module Program Sub Main(args As String()) Dim x = B.$$ End Sub Dim B As New B() End Module Class C Public X As Integer = 1 Public Shared Y As Integer = 2 End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "X") Await VerifyItemIsAbsentAsync(text, "Y") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType() As Task Dim text = <code><![CDATA[ MustInherit Class Test Private _field As Integer NotInheritable Class InnerTest Inherits Test Sub SomeTest() Dim x = $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "_field") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType2() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() $$ ' M recommended and accessible End Sub Class NN Sub Test2() ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType3() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() ' M recommended and accessible End Sub Class NN Sub Test2() $$ ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType4() As Task Dim text = <code><![CDATA[ Class C(Of T) Sub M() End Sub Class N Inherits C(Of Integer) Sub Test() M() ' M recommended and accessible End Sub Class NN Inherits N Sub Test2() $$ ' M inaccessible and not recommended End Function End Class End Class End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "M") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType5() As Task Dim text = <code><![CDATA[ Class D Public Sub Q() End Sub End Class Class C(Of T) Inherits D Class N Sub Test() $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Q") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestInstanceMembersFromBaseOuterType6() As Task Dim text = <code><![CDATA[ Class Base(Of T) Public X As Integer End Class Class Derived Inherits C(Of Integer) Class Nested Sub Test() $$ End Sub End Class End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "X") End Function <WorkItem(4900, "https://github.com/dotnet/roslyn/issues/4090")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoInstanceMembersWhenDottingIntoType() As Task Dim text = <code><![CDATA[ Class Instance Public Shared x as Integer Public y as Integer End Class Class Program Sub Goo() Instance.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "y") Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(4900, "https://github.com/dotnet/roslyn/issues/4090")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoSharedMemberWhenDottingIntoInstance() As Task Dim text = <code><![CDATA[ Class Instance Public Shared x as Integer Public y as Integer End Class Class Program Sub Goo() Dim x = new Instance() x.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") Await VerifyItemExistsAsync(text, "y") End Function <WorkItem(4136, "https://github.com/dotnet/roslyn/issues/4136")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoValue__WhenDottingIntoEnum() As Task Dim text = <code><![CDATA[ Enum E A End Enum Class Program Sub Goo() E.$$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "A") Await VerifyItemIsAbsentAsync(text, "value__") End Function <WorkItem(4136, "https://github.com/dotnet/roslyn/issues/4136")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNoValue__WhenDottingIntoLocalOfEnumType() As Task Dim text = <code><![CDATA[ Enum E A End Enum Class Program Sub Goo() Dim x = E.A x.$$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "value__") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function SharedProjectFieldAndPropertiesTreatedAsIdentical() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="ONE=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #if ONE Then Public x As Integer #endif #if TWO Then Public Property x as Integer #endif Sub goo() x$$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2" PreprocessorSymbols="TWO=True"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"({ FeaturesResources.field }) C.x As Integer" Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <Fact(), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSharedProjectFieldAndPropertiesTreatedAsIdentical2() As Task Dim markup = <Workspace> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj1" PreprocessorSymbols="ONE=True"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Class C #if TWO Then Public x As Integer #endif #if ONE Then Public Property x as Integer #endif Sub goo() x$$ End Sub End Class]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="True" AssemblyName="Proj2" PreprocessorSymbols="TWO=True"> <Document IsLinkFile="True" LinkAssemblyName="Proj1" LinkFilePath="CurrentDocument.vb"/> </Project> </Workspace>.ToString().NormalizeLineEndings() Dim expectedDescription = $"Property C.x As Integer" Await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription) End Function <WorkItem(4405, "https://github.com/dotnet/roslyn/issues/4405")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function VerifyDelegateEscapedWhenCommitted() As Task Dim text = <code><![CDATA[ Imports System Module Module1 Sub Main() Dim x As {0} End Sub End Module ]]></code>.Value Await VerifyProviderCommitAsync(markupBeforeCommit:=String.Format(text, "$$"), itemToCommit:="Delegate", expectedCodeAfterCommit:=String.Format(text, "[Delegate]"), commitChar:=Nothing) End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInExpressionContext1() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) args.Select($$) End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInExpressionContext2() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncExcludedInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInGetType() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) GetType($$) End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInTypeOf() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s = TypeOf args Is $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInReturnTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function x() as $$ End Function End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemFuncIncludedInFieldTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim x as $$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Func", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemDelegateInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Delegate") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInExpressionContext1() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) args.Select($$) End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInExpressionContext2() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionExcludedInStatementContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInGetType() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) GetType($$) End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInTypeOf() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim s = TypeOf args Is $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInReturnTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function x() as $$ End Function End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemActionIncludedInFieldTypeContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Dim x as $$ End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Action", displayTextSuffix:="(Of " & s_unicodeEllipsis & ")") End Function <WorkItem(4428, "https://github.com/dotnet/roslyn/issues/4428")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestSystemDelegateInExpressionContext() As Task Dim text = <code><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main() Dim x = $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Delegate") End Function <WorkItem(4750, "https://github.com/dotnet/roslyn/issues/4750")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalAccessInWith1() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim s As String With s 1: Console.WriteLine(If(?.$$, -1)) Console.WriteLine() End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(4750, "https://github.com/dotnet/roslyn/issues/4750")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestConditionalAccessInWith2() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim s As String With s 1: Console.WriteLine(If(?.Length, -1)) ?.$$ Console.WriteLine() End With End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(3290, "https://github.com/dotnet/roslyn/issues/3290")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestDotAfterArray() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim x = {1}.$$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "Length") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function LocalInForLoop() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim x As Integer For $$ End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeConstLocalInForLoop() As Task Dim text = <code><![CDATA[ Module Program Sub Main(args As String()) Dim const x As Integer For $$ End Sub End Module ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeConstFieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program Const x As Integer = 0 Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExcludeReadOnlyFieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program ReadOnly x As Integer Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function FieldInForLoop() As Task Dim text = <code><![CDATA[ Class Program Dim x As Integer Sub Main(args As String()) For $$ End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(text, "x") End Function <WorkItem(153633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/153633")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function EnumMembers() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Do Until (System.Console.ReadKey.Key = System.ConsoleKey.$$ Loop End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "A") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TupleElements() As Task Dim text = <code><![CDATA[ Module Module1 Sub Main() Dim t = (Alice:=1, Item2:=2, ITEM3:=3, 4, 5, 6, 7, 8, Bob:=9) t.$$ End Sub End Module Namespace System Public Structure ValueTuple(Of T1, T2) Public Sub New(item1 As T1, item2 As T2) End Sub End Structure Public Structure ValueTuple(Of T1, T2, T3, T4, T5, T6, T7, TRest) Public Dim Rest As TRest Public Sub New(item1 As T1, item2 As T2, item3 As T3, item4 As T4, item5 As T5, item6 As T6, item7 As T7, rest As TRest) End Sub Public Overrides Function ToString() As String Return "" End Function Public Overrides Function GetHashCode As Integer Return 0 End Function Public Overrides Function CompareTo(value As Object) As Integer Return 0 End Function Public Overrides Function GetType As Type Return Nothing End Function End Structure End Namespace ]]></code>.Value Await VerifyItemExistsAsync(text, "Alice") Await VerifyItemExistsAsync(text, "Bob") Await VerifyItemExistsAsync(text, "CompareTo") Await VerifyItemExistsAsync(text, "Equals") Await VerifyItemExistsAsync(text, "GetHashCode") Await VerifyItemExistsAsync(text, "GetType") For index = 2 To 8 Await VerifyItemExistsAsync(text, "Item" + index.ToString()) Next Await VerifyItemExistsAsync(text, "ToString") Await VerifyItemIsAbsentAsync(text, "Item1") Await VerifyItemIsAbsentAsync(text, "Item9") Await VerifyItemIsAbsentAsync(text, "Rest") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function WinformsInstanceMembers() As Task ' Setting the the preprocessor symbol _MyType=WindowsForms will cause the ' compiler to automatically generate the My Template. See ' GroupClassTests.vb for the compiler layer equivalent of these tests. Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="_MyType=WindowsForms"> <Document name="Form.vb"> <![CDATA[ Namespace Global.System.Windows.Forms Public Class Form Implements IDisposable Public Sub InstanceMethod() End Sub Public Shared Sub SharedMethod() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub Public ReadOnly Property IsDisposed As Boolean Get Return False End Get End Property End Class End Namespace ]]></Document> <Document name="types.vb"><![CDATA[ Imports System Namespace Global.WindowsApplication1 Public Class Form2 Inherits System.Windows.Forms.Form End Class End Namespace Namespace Global.WindowsApplication1 Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Goo() Form2.$$ End Sub End Class End Namespace ]]></Document> </Project> </Workspace> Using workspace = TestWorkspace.Create(input, exportProvider:=ExportProvider) Dim document = workspace.CurrentSolution.GetDocument(workspace.DocumentWithCursor.Id) Dim position = workspace.DocumentWithCursor.CursorPosition.Value Await CheckResultsAsync(document, position, "InstanceMethod", expectedDescriptionOrNull:=Nothing, usePreviousCharAsTrigger:=False, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionModeItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, inlineDescription:=Nothing, isComplexTextEdit:=Nothing, matchingFilters:=Nothing, flags:=Nothing) Await CheckResultsAsync(document, position, "SharedMethod", expectedDescriptionOrNull:=Nothing, usePreviousCharAsTrigger:=False, checkForAbsence:=False, glyph:=Nothing, matchPriority:=Nothing, hasSuggestionModeItem:=Nothing, displayTextSuffix:=Nothing, displayTextPrefix:=Nothing, inlineDescription:=Nothing, isComplexTextEdit:=Nothing, matchingFilters:=Nothing, flags:=Nothing) End Using End Function <WorkItem(22002, "https://github.com/dotnet/roslyn/issues/22002")> <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function DoNotCrashInTupleAlias() As Task Dim text = <code><![CDATA[ Imports Boom = System.Collections.Generic.List(Of ($$) '<---put caret between brackets. Public Module Module1 Public Sub Main() End Sub End Module ]]></code>.Value Await VerifyItemExistsAsync(text, "System") End Function Private Shared Function CreateThenIncludeTestCode(lambdaExpressionString As String, methodDeclarationString As String) As String Dim template = " Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Linq.Expressions Namespace ThenIncludeIntellisenseBug Class Program Shared Sub Main(args As String()) Dim registrations = New List(Of Registration)().AsQueryable() Dim reg = registrations.Include(Function(r) r.Activities).ThenInclude([1]) End Sub End Class Friend Class Registration Public Property Activities As ICollection(Of Activity) End Class Public Class Activity Public Property Task As Task End Class Public Class Task Public Property Name As String End Class Public Interface IIncludableQueryable(Of Out TEntity, Out TProperty) Inherits IQueryable(Of TEntity) End Interface Public Module EntityFrameworkQuerybleExtensions <System.Runtime.CompilerServices.Extension> Public Function Include(Of TEntity, TProperty)( source As IQueryable(Of TEntity), navigationPropertyPath As Expression(Of Func(Of TEntity, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function [2] End Module End Namespace" Return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenInclude() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeNoExpression() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Func(Of TPreviousProperty, TProperty)) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Func(Of TPreviousProperty, TProperty)) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgument() As Task Dim source = CreateThenIncludeTestCode("0, Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentAndMultiArgumentLambda() As Task Dim source = CreateThenIncludeTestCode("0, Function(a, b, c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentNoOverlap() As Task Dim source = CreateThenIncludeTestCode("Function(b) b.Task, Function(b) b.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty)), anotherNavigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() As Task Dim source = CreateThenIncludeTestCode("0, Function(a, b, c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, ICollection(Of TPreviousProperty)), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), a as Integer, navigationPropertyPath As Expression(Of Func(Of string, string, TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemIsAbsentAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact(Skip:="https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeGenericAndNoGenericOverloads() As Task Dim source = CreateThenIncludeTestCode("Function(c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Func(Of Activity, Task)) As IIncludableQueryable(Of Registration, Task) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude(Of TEntity, TPreviousProperty, TProperty)( source As IIncludableQueryable(Of TEntity, TPreviousProperty), navigationPropertyPath As Expression(Of Func(Of TPreviousProperty, TProperty))) As IIncludableQueryable(Of TEntity, TProperty) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ThenIncludeNoGenericOverloads() As Task Dim source = CreateThenIncludeTestCode("Function(c) c.$$", " <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Func(Of Activity, Task)) As IIncludableQueryable(Of Registration, Task) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function ThenInclude( source As IIncludableQueryable(Of Registration, ICollection(Of Activity)), navigationPropertyPath As Expression(Of Func(Of ICollection(Of Activity), Activity))) As IIncludableQueryable(Of Registration, Activity) Return Nothing End Function ") Await VerifyItemExistsAsync(source, "Task") Await VerifyItemExistsAsync(source, "FirstOrDefault") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionForLambdaWithOverloads() As Task Dim source = <code><![CDATA[ Imports System.Linq.Expressions Imports System.Collections Imports System Imports System.Collections.Generic Namespace VBTest Public Class SomeItem Public A As String Public B As Integer End Class Class SomeCollection(Of T) Inherits List(Of T) Public Overridable Function Include(path As String) As SomeCollection(Of T) Return Nothing End Function End Class Module Extensions <System.Runtime.CompilerServices.Extension> Public Function Include(Of T, TProperty)(ByVal source As IList(Of T), path As Expression(Of Func(Of T, TProperty))) As IList(Of T) Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function Include(ByVal source As IList, path As String) As IList Return Nothing End Function <System.Runtime.CompilerServices.Extension> Public Function Include(Of T)(ByVal source As IList(Of T), path As String) As IList(Of T) Return Nothing End Function End Module Class Program Sub M(c As SomeCollection(Of SomeItem)) Dim a = From m In c.Include(Function(t) t.$$) End Sub End Class End Namespace ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "A") Await VerifyItemExistsAsync(source, "B") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads2() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As String) End Sub Sub Test() M(Sub(a) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads3() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As Action(Of String)) End Sub Sub Test() M(Sub(a as Integer) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")> Public Async Function CompletionForLambdaWithOverloads4() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M(a As Action(Of Integer)) End Sub Sub M(a As Action(Of String)) End Sub Sub Test() M(Sub(a) a.$$) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Substring") Await VerifyItemExistsAsync(source, "GetTypeCode") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(y:=Sub(x) x.$$ End Sub) End Sub Sub M(Optional x As Integer = 0, Optional y As Action(Of String) = Nothing) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(z:=Sub(x) x.$$ End Sub) End Sub Sub M(x As Integer, y As Integer, z As Action(Of String)) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")> Public Async Function CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameterWithDifferentCasing() As Task Dim source = <code><![CDATA[ Imports System Class C Sub Test() M(Z:=Sub(x) x.$$ End Sub) End Sub Sub M(x As Integer, y As Integer, z As Action(Of String)) End Sub End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Length") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithNonFunctionsAsArguments() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Sub(b) b.$$ End Sub Sub Goo(configure As Action(Of Builder)) Dim builder = New Builder() configure(builder) End Sub End Class Class Builder Public Property Something As Integer End Class ]]></code>.Value Await VerifyItemExistsAsync(source, "Something") Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithDelegatesAsArguments() As Task Dim source = <code><![CDATA[ Imports System Module Module2 Class Program Public Delegate Sub Delegate1(u As Uri) Public Delegate Sub Delegate2(g As Guid) Public Sub M(d As Delegate1) End Sub Public Sub M(d As Delegate2) End Sub Public Sub Test() M(Sub(d) d.$$) End Sub End Class End Module ]]></code>.Value ' Guid Await VerifyItemExistsAsync(source, "ToByteArray") ' Uri Await VerifyItemExistsAsync(source, "AbsoluteUri") Await VerifyItemExistsAsync(source, "Fragment") Await VerifyItemExistsAsync(source, "Query") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionInsideMethodsWithDelegatesAndReversingArguments() As Task Dim source = <code><![CDATA[ Imports System Module Module2 Class Program Public Delegate Sub Delegate1(Of T1, T2)(t2 As T2, t1 As T1) Public Delegate Sub Delegate2(Of T1, T2)(t2 As T2, a As Integer, t1 As T1) Public Sub M(d As Delegate1(Of Uri, Guid)) End Sub Public Sub M(d As Delegate2(Of Uri, Guid)) End Sub Public Sub Test() M(Sub(d) d.$$) End Sub End Class End Module ]]></code>.Value ' Guid Await VerifyItemExistsAsync(source, "ToByteArray") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "AbsoluteUri") Await VerifyItemIsAbsentAsync(source, "Fragment") Await VerifyItemIsAbsentAsync(source, "Query") ' Should Not appear for Delegate Await VerifyItemIsAbsentAsync(source, "BeginInvoke") Await VerifyItemIsAbsentAsync(source, "Clone") Await VerifyItemIsAbsentAsync(source, "Method") Await VerifyItemIsAbsentAsync(source, "Target") End Function <WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")> <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function CompletionInsideMethodWithParamsBeforeParams() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Sub(b) b.$$) End Sub Sub Goo(action As Action(Of Builder), ParamArray otherActions() As Action(Of AnotherBuilder)) End Sub End Class Class Builder Public Something As Integer End Class Class AnotherBuilder Public AnotherSomething As Integer End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "AnotherSomething") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") Await VerifyItemExistsAsync(source, "Something") End Function <WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")> <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function CompletionInsideMethodWithParamsInParams() As Task Dim source = <code><![CDATA[ Imports System Class C Sub M() Goo(Nothing, Nothing, Sub(b) b.$$) End Sub Sub Goo(action As Action(Of Builder), ParamArray otherActions() As Action(Of AnotherBuilder)) End Sub End Class Class Builder Public Something As Integer End Class Class AnotherBuilder Public AnotherSomething As Integer End Class ]]></code>.Value Await VerifyItemIsAbsentAsync(source, "Something") Await VerifyItemIsAbsentAsync(source, "FirstOrDefault") Await VerifyItemExistsAsync(source, "AnotherSomething") End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestTargetTypeFilterWithExperimentEnabled() As Task TargetTypedCompletionFilterFeatureFlag = True Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "intField", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.FieldFilter, FilterSet.TargetTypedFilter}) End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestNoTargetTypeFilterWithExperimentDisabled() As Task TargetTypedCompletionFilterFeatureFlag = False Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "intField", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.FieldFilter}) End Function <Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)> Public Async Function TestTargetTypeFilter_NotOnObjectMembers() As Task TargetTypedCompletionFilterFeatureFlag = True Dim markup = "Class C Dim intField As Integer Sub M(x as Integer) M($$) End Sub End Class" Await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters:=New List(Of CompletionFilter) From {FilterSet.MethodFilter}) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/Core/Portable/SourceGeneration/GeneratorState.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.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the current state of a generator /// </summary> internal readonly struct GeneratorState { /// <summary> /// Creates a new generator state that just contains information /// </summary> public GeneratorState(GeneratorInfo info) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty) { } /// <summary> /// Creates a new generator state that contains information and constant trees /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees) : this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty) { } /// <summary> /// Creates a new generator state that contains information, constant trees and an execution pipeline /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes) : this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null, elapsedTime: TimeSpan.Zero) { } /// <summary> /// Creates a new generator state that contains an exception and the associated diagnostic /// </summary> public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error, TimeSpan elapsedTime) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e, elapsedTime) { } /// <summary> /// Creates a generator state that contains results /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, TimeSpan elapsedTime) : this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null, elapsedTime) { } private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception, TimeSpan elapsedTime) { this.Initialized = true; this.PostInitTrees = postInitTrees; this.InputNodes = inputNodes; this.OutputNodes = outputNodes; this.GeneratedTrees = generatedTrees; this.Info = info; this.Diagnostics = diagnostics; this.Exception = exception; this.ElapsedTime = elapsedTime; } internal bool Initialized { get; } internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; } internal ImmutableArray<ISyntaxInputNode> InputNodes { get; } internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; } internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; } internal GeneratorInfo Info { get; } internal Exception? Exception { get; } internal TimeSpan ElapsedTime { get; } internal ImmutableArray<Diagnostic> Diagnostics { 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; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents the current state of a generator /// </summary> internal readonly struct GeneratorState { /// <summary> /// Creates a new generator state that just contains information /// </summary> public GeneratorState(GeneratorInfo info) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty) { } /// <summary> /// Creates a new generator state that contains information and constant trees /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees) : this(info, postInitTrees, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty) { } /// <summary> /// Creates a new generator state that contains information, constant trees and an execution pipeline /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes) : this(info, postInitTrees, inputNodes, outputNodes, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<Diagnostic>.Empty, exception: null, elapsedTime: TimeSpan.Zero) { } /// <summary> /// Creates a new generator state that contains an exception and the associated diagnostic /// </summary> public GeneratorState(GeneratorInfo info, Exception e, Diagnostic error, TimeSpan elapsedTime) : this(info, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray<ISyntaxInputNode>.Empty, ImmutableArray<IIncrementalGeneratorOutputNode>.Empty, ImmutableArray<GeneratedSyntaxTree>.Empty, ImmutableArray.Create(error), exception: e, elapsedTime) { } /// <summary> /// Creates a generator state that contains results /// </summary> public GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, TimeSpan elapsedTime) : this(info, postInitTrees, inputNodes, outputNodes, generatedTrees, diagnostics, exception: null, elapsedTime) { } private GeneratorState(GeneratorInfo info, ImmutableArray<GeneratedSyntaxTree> postInitTrees, ImmutableArray<ISyntaxInputNode> inputNodes, ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, ImmutableArray<GeneratedSyntaxTree> generatedTrees, ImmutableArray<Diagnostic> diagnostics, Exception? exception, TimeSpan elapsedTime) { this.Initialized = true; this.PostInitTrees = postInitTrees; this.InputNodes = inputNodes; this.OutputNodes = outputNodes; this.GeneratedTrees = generatedTrees; this.Info = info; this.Diagnostics = diagnostics; this.Exception = exception; this.ElapsedTime = elapsedTime; } internal bool Initialized { get; } internal ImmutableArray<GeneratedSyntaxTree> PostInitTrees { get; } internal ImmutableArray<ISyntaxInputNode> InputNodes { get; } internal ImmutableArray<IIncrementalGeneratorOutputNode> OutputNodes { get; } internal ImmutableArray<GeneratedSyntaxTree> GeneratedTrees { get; } internal GeneratorInfo Info { get; } internal Exception? Exception { get; } internal TimeSpan ElapsedTime { get; } internal ImmutableArray<Diagnostic> Diagnostics { get; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/PropertyDeclarationStructureTests.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 PropertyDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of PropertyStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New PropertyDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Property $$Goo As Integer End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|textspan:<Goo> |}Property $$Goo As Integer|} End Class " 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 = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Public Property $$Goo As Integer|} End Class " 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 PropertyDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of PropertyStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New PropertyDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Property $$Goo As Integer End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|textspan:<Goo> |}Property $$Goo As Integer|} End Class " 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 = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Public Property $$Goo As Integer|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_InvalidExpression.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 Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_BadReceiver() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Console.WriteLine2()'BIND:"Console.WriteLine2()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Console') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30456: 'WriteLine2' is not a member of 'Console'. Console.WriteLine2()'BIND:"Console.WriteLine2()" ~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_OverloadResolutionFailureBadArgument() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) F(String.Empty)'BIND:"F(String.Empty)" End Sub Private Sub F(x As Integer) End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation ( Sub Program.F(x As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F(String.Empty)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'F') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'String.Empty') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'String.Empty') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'String.Empty') Instance Receiver: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. F(String.Empty)'BIND:"F(String.Empty)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) F(String.Empty)'BIND:"F(String.Empty)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(String.Empty)') Children(2): IOperation: (OperationKind.None, Type: null) (Syntax: 'F') Children(1): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'F') IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'String.Empty') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Private Sub F()'. F(String.Empty)'BIND:"F(String.Empty)" ~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidFieldReferenceExpression() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Dim y = x.MissingField'BIND:"x.MissingField" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30456: 'MissingField' is not a member of 'Program'. Dim y = x.MissingField'BIND:"x.MissingField" ~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidConversionExpression_ImplicitCast() Dim source = <![CDATA[ Class Program Private i1 As Integer Public Shared Sub Main(args As String()) Dim x = New Program() Dim y As Program = x.i1'BIND:"x.i1" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: Program.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'Program'. Dim y As Program = x.i1'BIND:"x.i1" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidConversionExpression_ExplicitCast() Dim source = <![CDATA[ Class Program Private i1 As Integer Public Shared Sub Main(args As String()) Dim x = New Program() Dim y As Program = DirectCast(x.i1, Program)'BIND:"DirectCast(x.i1, Program)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: 'DirectCast( ... 1, Program)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: Program.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'Program'. Dim y As Program = DirectCast(x.i1, Program)'BIND:"DirectCast(x.i1, Program)" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidUnaryExpression() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Console.Write(+x)'BIND:"+x" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IUnaryOperation (UnaryOperatorKind.Plus, Checked) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+x') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30487: Operator '+' is not defined for type 'Program'. Console.Write(+x)'BIND:"+x" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidBinaryExpression() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Console.Write(x + (y * args.Length))'BIND:"x + (y * args.Length)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IParenthesizedOperation (OperationKind.Parenthesized, Type: ?, IsInvalid) (Syntax: '(y * args.Length)') Operand: IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Console.Write(x + (y * args.Length))'BIND:"x + (y * args.Length)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of BinaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidLambdaBinding_UnboundLambda() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = Function() F()'BIND:"Function() F()" End Sub Private Shared Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousFunctionOperation (Symbol: Function () As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() F()') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') Locals: Local_1: <anonymous local> As ? IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'F()') Children(1): IInvocationOperation (Sub Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Function() F()') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Dim x = Function() F()'BIND:"Function() F()" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of SingleLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidFieldInitializer() Dim source = <![CDATA[ Imports System.Collections.Generic Imports System.Linq Imports System.Threading.Tasks Class Program Private x As Integer = Program'BIND:"= Program" Public Shared Sub Main(args As String()) Dim x = New Program() With { .x = Program } End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializerOperation (Field: Program.x As System.Int32) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30109: 'Program' is a class type and cannot be used as an expression. Private x As Integer = Program'BIND:"= Program" ~~~~~~~ BC30109: 'Program' is a class type and cannot be used as an expression. .x = Program ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18074"), WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidArrayInitializer() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{1, 1}}') Element Values(1): IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '{1, 1}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 1 elements. Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" ~~~~~~~~ BC30566: Array initializer has too many dimensions. Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidArrayCreation() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationOperation (OperationKind.ArrayCreation, Type: X(), IsInvalid) (Syntax: 'New X(Program - 1) {{1}}') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'Program - 1') Left: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{{1}}') Element Values(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '{1}') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'X' is not defined. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~ BC30109: 'Program' is a class type and cannot be used as an expression. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~~~~~ BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~~~ BC30566: Array initializer has too many dimensions. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidParameterDefaultValueInitializer() Dim source = <![CDATA[ Class Program Private Shared Function M() As Integer Return 0 End Function Private Sub F(Optional p As Integer = M())'BIND:"= M()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterInitializerOperation (Parameter: [p As System.Int32]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Children(1): IInvocationOperation (Function Program.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Private Sub F(Optional p As Integer = M())'BIND:"= M()" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IInvalid_InstanceIndexerAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Default Public ReadOnly Property Item(i As Integer) As C1 'indexer Get Return Nothing End Get End Property End Class Sub S1() Dim a = C1(1)'BIND:"C1(1)" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'C1(1)') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30109: 'M1.C1' is a class type and cannot be used as an expression. Dim a = C1(1)'BIND:"C1(1)" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_01() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, y As Integer, z As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, y As Integer, z As Integer)" i = M(x, M2(y,z)) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,z)) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,z)) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2(y,z))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2(y,z))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(y,z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(y,z))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(y,z)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_02() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer)" i = M(x, M2(y,If(b,1,2))) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,If(b,1,2))) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,If(b,1,2))) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... If(b,1,2)))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... If(b,1,2)))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(y,If(b,1,2)))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(y,If(b,1,2)))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(y,If(b,1,2))') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'y') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_03() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer)" i = M(x, M2(If(b,1,2), y)) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), y)) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), y)) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... b,1,2), y))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... b,1,2), y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(If(b,1,2), y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(If(b,1,2), y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(If(b,1,2), y)') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_04() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, a As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, a As Boolean, y As Integer)" i = M(x, M2(If(b,1,2), If(a,3,4))) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), If(a,3,4))) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), If(a,3,4))) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... If(a,3,4)))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... If(a,3,4)))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(If( ... If(a,3,4)))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(If( ... If(a,3,4)))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(If(b,1,2), If(a,3,4))') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a,3,4)') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(35813, "https://github.com/dotnet/roslyn/issues/35813"), WorkItem(45382, "https://github.com/dotnet/roslyn/issues/45382")> Public Sub InvalidTypeArguments() Dim source = <![CDATA[ Class C Public Sub M(node As Object) node.ExtensionMethod(Of Object)() 'BIND:"node.ExtensionMethod(Of Object)()" End Sub End Class ]]>.Value Dim expectedStrictOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'node.Extens ... f Object)()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'node.Extens ... (Of Object)') Children(2): IParameterReferenceOperation: node (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'node') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '(Of Object)') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30574: Option Strict On disallows late binding. node.ExtensionMethod(Of Object)() 'BIND:"node.ExtensionMethod(Of Object)()" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)("Option Strict On" + Environment.NewLine + source, expectedStrictOperationTree, expectedDiagnostics) Dim expectedNonStrictOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'node.Extens ... f Object)()') Expression: IDynamicMemberReferenceOperation (Member Name: "ExtensionMethod", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'node.Extens ... (Of Object)') Type Arguments(1): Symbol: System.Object Instance Receiver: IParameterReferenceOperation: node (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'node') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)("Option Strict Off" + Environment.NewLine + source, expectedNonStrictOperationTree, expectedDiagnostics:=String.Empty) 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 Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_BadReceiver() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Console.WriteLine2()'BIND:"Console.WriteLine2()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Console') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30456: 'WriteLine2' is not a member of 'Console'. Console.WriteLine2()'BIND:"Console.WriteLine2()" ~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_OverloadResolutionFailureBadArgument() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) F(String.Empty)'BIND:"F(String.Empty)" End Sub Private Sub F(x As Integer) End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation ( Sub Program.F(x As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F(String.Empty)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'F') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'String.Empty') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'String.Empty') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'String.Empty') Instance Receiver: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. F(String.Empty)'BIND:"F(String.Empty)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) F(String.Empty)'BIND:"F(String.Empty)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(String.Empty)') Children(2): IOperation: (OperationKind.None, Type: null) (Syntax: 'F') Children(1): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'F') IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'String.Empty') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Private Sub F()'. F(String.Empty)'BIND:"F(String.Empty)" ~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidFieldReferenceExpression() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Dim y = x.MissingField'BIND:"x.MissingField" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30456: 'MissingField' is not a member of 'Program'. Dim y = x.MissingField'BIND:"x.MissingField" ~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidConversionExpression_ImplicitCast() Dim source = <![CDATA[ Class Program Private i1 As Integer Public Shared Sub Main(args As String()) Dim x = New Program() Dim y As Program = x.i1'BIND:"x.i1" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldReferenceOperation: Program.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'Program'. Dim y As Program = x.i1'BIND:"x.i1" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidConversionExpression_ExplicitCast() Dim source = <![CDATA[ Class Program Private i1 As Integer Public Shared Sub Main(args As String()) Dim x = New Program() Dim y As Program = DirectCast(x.i1, Program)'BIND:"DirectCast(x.i1, Program)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: 'DirectCast( ... 1, Program)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: Program.i1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30311: Value of type 'Integer' cannot be converted to 'Program'. Dim y As Program = DirectCast(x.i1, Program)'BIND:"DirectCast(x.i1, Program)" ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidUnaryExpression() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Console.Write(+x)'BIND:"+x" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IUnaryOperation (UnaryOperatorKind.Plus, Checked) (OperationKind.Unary, Type: ?, IsInvalid) (Syntax: '+x') Operand: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30487: Operator '+' is not defined for type 'Program'. Console.Write(+x)'BIND:"+x" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidBinaryExpression() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = New Program() Console.Write(x + (y * args.Length))'BIND:"x + (y * args.Length)" End Sub Private Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IParenthesizedOperation (OperationKind.Parenthesized, Type: ?, IsInvalid) (Syntax: '(y * args.Length)') Operand: IBinaryOperation (BinaryOperatorKind.Multiply, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'y' is not declared. It may be inaccessible due to its protection level. Console.Write(x + (y * args.Length))'BIND:"x + (y * args.Length)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of BinaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidLambdaBinding_UnboundLambda() Dim source = <![CDATA[ Imports System Class Program Public Shared Sub Main(args As String()) Dim x = Function() F()'BIND:"Function() F()" End Sub Private Shared Sub F() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IAnonymousFunctionOperation (Symbol: Function () As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() F()') IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') Locals: Local_1: <anonymous local> As ? IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'F()') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'F()') Children(1): IInvocationOperation (Sub Program.F()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'F()') Instance Receiver: null Arguments(0) ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() F()') ReturnedValue: ILocalReferenceOperation: (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Function() F()') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30491: Expression does not produce a value. Dim x = Function() F()'BIND:"Function() F()" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of SingleLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidFieldInitializer() Dim source = <![CDATA[ Imports System.Collections.Generic Imports System.Linq Imports System.Threading.Tasks Class Program Private x As Integer = Program'BIND:"= Program" Public Shared Sub Main(args As String()) Dim x = New Program() With { .x = Program } End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IFieldInitializerOperation (Field: Program.x As System.Int32) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30109: 'Program' is a class type and cannot be used as an expression. Private x As Integer = Program'BIND:"= Program" ~~~~~~~ BC30109: 'Program' is a class type and cannot be used as an expression. .x = Program ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18074"), WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidArrayInitializer() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayInitializer (1 elements) (OperationKind.ArrayInitializer, IsInvalid) (Syntax: '{{1, 1}}') Element Values(1): IInvalidExpression (OperationKind.InvalidExpression, Type: ?, IsInvalid) (Syntax: '{1, 1}') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30567: Array initializer is missing 1 elements. Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" ~~~~~~~~ BC30566: Array initializer has too many dimensions. Dim x = New Integer(1, 1) {{{1, 1}}, {2, 2}}'BIND:"{{1, 1}}" ~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of CollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidArrayCreation() Dim source = <![CDATA[ Class Program Public Shared Sub Main(args As String()) Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IArrayCreationOperation (OperationKind.ArrayCreation, Type: X(), IsInvalid) (Syntax: 'New X(Program - 1) {{1}}') Dimension Sizes(1): IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'Program - 1') Left: IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'Program - 1') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{{1}}') Element Values(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: '{1}') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'X' is not defined. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~ BC30109: 'Program' is a class type and cannot be used as an expression. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~~~~~ BC30949: Array initializer cannot be specified for a non constant dimension; use the empty initializer '{}'. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~~~ BC30566: Array initializer has too many dimensions. Dim x = New X(Program - 1) {{1}}'BIND:"New X(Program - 1) {{1}}" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ArrayCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")> Public Sub InvalidParameterDefaultValueInitializer() Dim source = <![CDATA[ Class Program Private Shared Function M() As Integer Return 0 End Function Private Sub F(Optional p As Integer = M())'BIND:"= M()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IParameterInitializerOperation (Parameter: [p As System.Int32]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()') Children(1): IInvocationOperation (Function Program.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30059: Constant expression is required. Private Sub F(Optional p As Integer = M())'BIND:"= M()" ~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IInvalid_InstanceIndexerAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Default Public ReadOnly Property Item(i As Integer) As C1 'indexer Get Return Nothing End Get End Property End Class Sub S1() Dim a = C1(1)'BIND:"C1(1)" End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'C1(1)') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30109: 'M1.C1' is a class type and cannot be used as an expression. Dim a = C1(1)'BIND:"C1(1)" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_01() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, y As Integer, z As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, y As Integer, z As Integer)" i = M(x, M2(y,z)) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,z)) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,z)) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2(y,z))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2(y,z))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(y,z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(y,z))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(y,z)') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_02() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer)" i = M(x, M2(y,If(b,1,2))) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,If(b,1,2))) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(y,If(b,1,2))) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... If(b,1,2)))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... If(b,1,2)))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(y,If(b,1,2)))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(y,If(b,1,2)))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(y,If(b,1,2))') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'y') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_03() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, y As Integer)" i = M(x, M2(If(b,1,2), y)) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), y)) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), y)) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... b,1,2), y))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... b,1,2), y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(If(b,1,2), y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(If(b,1,2), y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(If(b,1,2), y)') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub InvalidExpressionFlow_04() Dim source = <![CDATA[ Imports System Public Class C Public Sub M1(i As Integer, x As Integer, b As Boolean, a As Boolean, y As Integer) 'BIND:"Public Sub M1(i As Integer, x As Integer, b As Boolean, a As Boolean, y As Integer)" i = M(x, M2(If(b,1,2), If(a,3,4))) End Sub End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'M' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), If(a,3,4))) ~ BC30451: 'M2' is not declared. It may be inaccessible due to its protection level. i = M(x, M2(If(b,1,2), If(a,3,4))) ~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] [5] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2') Children(0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(x, M2 ... If(a,3,4)))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'i = M(x, M2 ... If(a,3,4)))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(x, M2(If( ... If(a,3,4)))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (DelegateRelaxationLevelNone) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(x, M2(If( ... If(a,3,4)))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M2(If(b,1,2), If(a,3,4))') Children(3): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M2') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(b,1,2)') IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a,3,4)') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(35813, "https://github.com/dotnet/roslyn/issues/35813"), WorkItem(45382, "https://github.com/dotnet/roslyn/issues/45382")> Public Sub InvalidTypeArguments() Dim source = <![CDATA[ Class C Public Sub M(node As Object) node.ExtensionMethod(Of Object)() 'BIND:"node.ExtensionMethod(Of Object)()" End Sub End Class ]]>.Value Dim expectedStrictOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'node.Extens ... f Object)()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'node.Extens ... (Of Object)') Children(2): IParameterReferenceOperation: node (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'node') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '(Of Object)') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30574: Option Strict On disallows late binding. node.ExtensionMethod(Of Object)() 'BIND:"node.ExtensionMethod(Of Object)()" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)("Option Strict On" + Environment.NewLine + source, expectedStrictOperationTree, expectedDiagnostics) Dim expectedNonStrictOperationTree = <![CDATA[ IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'node.Extens ... f Object)()') Expression: IDynamicMemberReferenceOperation (Member Name: "ExtensionMethod", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'node.Extens ... (Of Object)') Type Arguments(1): Symbol: System.Object Instance Receiver: IParameterReferenceOperation: node (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'node') Arguments(0) ArgumentNames(0) ArgumentRefKinds: null ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)("Option Strict Off" + Environment.NewLine + source, expectedNonStrictOperationTree, expectedDiagnostics:=String.Empty) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Utilities/Documentation/XmlDocumentationProvider.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.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class used to provide XML documentation to the compiler for members from metadata from an XML document source. /// </summary> public abstract class XmlDocumentationProvider : DocumentationProvider { private readonly NonReentrantLock _gate = new(); private Dictionary<string, string> _docComments; /// <summary> /// Gets the source stream for the XML document. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected abstract Stream GetSourceStream(CancellationToken cancellationToken); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from bytes representing XML documentation data. /// </summary> /// <param name="xmlDocCommentBytes">The XML document bytes.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromBytes(byte[] xmlDocCommentBytes) => new ContentBasedXmlDocumentationProvider(xmlDocCommentBytes); private static XmlDocumentationProvider DefaultXmlDocumentationProvider { get; } = new NullXmlDocumentationProvider(); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from an XML documentation file. /// </summary> /// <param name="xmlDocCommentFilePath">The path to the XML file.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromFile(string xmlDocCommentFilePath) { if (!File.Exists(xmlDocCommentFilePath)) { return DefaultXmlDocumentationProvider; } return new FileBasedXmlDocumentationProvider(xmlDocCommentFilePath); } private XDocument GetXDocument(CancellationToken cancellationToken) { using var stream = GetSourceStream(cancellationToken); using var xmlReader = XmlReader.Create(stream, s_xmlSettings); return XDocument.Load(xmlReader); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) { if (_docComments == null) { using (_gate.DisposableWait(cancellationToken)) { try { var comments = new Dictionary<string, string>(); var doc = GetXDocument(cancellationToken); foreach (var e in doc.Descendants("member")) { if (e.Attribute("name") != null) { using var reader = e.CreateReader(); reader.MoveToContent(); comments[e.Attribute("name").Value] = reader.ReadInnerXml(); } } _docComments = comments; } catch (Exception) { _docComments = new Dictionary<string, string>(); } } } return _docComments.TryGetValue(documentationMemberID, out var docComment) ? docComment : ""; } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private sealed class ContentBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly byte[] _xmlDocCommentBytes; public ContentBasedXmlDocumentationProvider(byte[] xmlDocCommentBytes) { Contract.ThrowIfNull(xmlDocCommentBytes); _xmlDocCommentBytes = xmlDocCommentBytes; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => SerializableBytes.CreateReadableStream(_xmlDocCommentBytes); public override bool Equals(object obj) { var other = obj as ContentBasedXmlDocumentationProvider; return other != null && EqualsHelper(other); } private bool EqualsHelper(ContentBasedXmlDocumentationProvider other) { // Check for reference equality first if (this == other || _xmlDocCommentBytes == other._xmlDocCommentBytes) { return true; } // Compare byte sequences if (_xmlDocCommentBytes.Length != other._xmlDocCommentBytes.Length) { return false; } for (var i = 0; i < _xmlDocCommentBytes.Length; i++) { if (_xmlDocCommentBytes[i] != other._xmlDocCommentBytes[i]) { return false; } } return true; } public override int GetHashCode() => Hash.CombineValues(_xmlDocCommentBytes); } private sealed class FileBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly string _filePath; public FileBasedXmlDocumentationProvider(string filePath) { Contract.ThrowIfNull(filePath); Debug.Assert(PathUtilities.IsAbsolute(filePath)); _filePath = filePath; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => new FileStream(_filePath, FileMode.Open, FileAccess.Read); public override bool Equals(object obj) { var other = obj as FileBasedXmlDocumentationProvider; return other != null && _filePath == other._filePath; } public override int GetHashCode() => _filePath.GetHashCode(); } /// <summary> /// A trivial XmlDocumentationProvider which never returns documentation. /// </summary> private sealed class NullXmlDocumentationProvider : XmlDocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) => ""; protected override Stream GetSourceStream(CancellationToken cancellationToken) => new MemoryStream(); public override bool Equals(object obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() => 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. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class used to provide XML documentation to the compiler for members from metadata from an XML document source. /// </summary> public abstract class XmlDocumentationProvider : DocumentationProvider { private readonly NonReentrantLock _gate = new(); private Dictionary<string, string> _docComments; /// <summary> /// Gets the source stream for the XML document. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected abstract Stream GetSourceStream(CancellationToken cancellationToken); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from bytes representing XML documentation data. /// </summary> /// <param name="xmlDocCommentBytes">The XML document bytes.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromBytes(byte[] xmlDocCommentBytes) => new ContentBasedXmlDocumentationProvider(xmlDocCommentBytes); private static XmlDocumentationProvider DefaultXmlDocumentationProvider { get; } = new NullXmlDocumentationProvider(); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from an XML documentation file. /// </summary> /// <param name="xmlDocCommentFilePath">The path to the XML file.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromFile(string xmlDocCommentFilePath) { if (!File.Exists(xmlDocCommentFilePath)) { return DefaultXmlDocumentationProvider; } return new FileBasedXmlDocumentationProvider(xmlDocCommentFilePath); } private XDocument GetXDocument(CancellationToken cancellationToken) { using var stream = GetSourceStream(cancellationToken); using var xmlReader = XmlReader.Create(stream, s_xmlSettings); return XDocument.Load(xmlReader); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) { if (_docComments == null) { using (_gate.DisposableWait(cancellationToken)) { try { var comments = new Dictionary<string, string>(); var doc = GetXDocument(cancellationToken); foreach (var e in doc.Descendants("member")) { if (e.Attribute("name") != null) { using var reader = e.CreateReader(); reader.MoveToContent(); comments[e.Attribute("name").Value] = reader.ReadInnerXml(); } } _docComments = comments; } catch (Exception) { _docComments = new Dictionary<string, string>(); } } } return _docComments.TryGetValue(documentationMemberID, out var docComment) ? docComment : ""; } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private sealed class ContentBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly byte[] _xmlDocCommentBytes; public ContentBasedXmlDocumentationProvider(byte[] xmlDocCommentBytes) { Contract.ThrowIfNull(xmlDocCommentBytes); _xmlDocCommentBytes = xmlDocCommentBytes; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => SerializableBytes.CreateReadableStream(_xmlDocCommentBytes); public override bool Equals(object obj) { var other = obj as ContentBasedXmlDocumentationProvider; return other != null && EqualsHelper(other); } private bool EqualsHelper(ContentBasedXmlDocumentationProvider other) { // Check for reference equality first if (this == other || _xmlDocCommentBytes == other._xmlDocCommentBytes) { return true; } // Compare byte sequences if (_xmlDocCommentBytes.Length != other._xmlDocCommentBytes.Length) { return false; } for (var i = 0; i < _xmlDocCommentBytes.Length; i++) { if (_xmlDocCommentBytes[i] != other._xmlDocCommentBytes[i]) { return false; } } return true; } public override int GetHashCode() => Hash.CombineValues(_xmlDocCommentBytes); } private sealed class FileBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly string _filePath; public FileBasedXmlDocumentationProvider(string filePath) { Contract.ThrowIfNull(filePath); Debug.Assert(PathUtilities.IsAbsolute(filePath)); _filePath = filePath; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => new FileStream(_filePath, FileMode.Open, FileAccess.Read); public override bool Equals(object obj) { var other = obj as FileBasedXmlDocumentationProvider; return other != null && _filePath == other._filePath; } public override int GetHashCode() => _filePath.GetHashCode(); } /// <summary> /// A trivial XmlDocumentationProvider which never returns documentation. /// </summary> private sealed class NullXmlDocumentationProvider : XmlDocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) => ""; protected override Stream GetSourceStream(CancellationToken cancellationToken) => new MemoryStream(); public override bool Equals(object obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() => 0; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Symbols/EmbeddableAttributes.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.CSharp { [Flags] internal enum EmbeddableAttributes { IsReadOnlyAttribute = 0x01, IsByRefLikeAttribute = 0x02, IsUnmanagedAttribute = 0x04, NullableAttribute = 0x08, NullableContextAttribute = 0x10, NullablePublicOnlyAttribute = 0x20, NativeIntegerAttribute = 0x40, } }
// 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.CSharp { [Flags] internal enum EmbeddableAttributes { IsReadOnlyAttribute = 0x01, IsByRefLikeAttribute = 0x02, IsUnmanagedAttribute = 0x04, NullableAttribute = 0x08, NullableContextAttribute = 0x10, NullablePublicOnlyAttribute = 0x20, NativeIntegerAttribute = 0x40, } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Def/Implementation/MoveToNamespace/MoveToNamespaceDialogViewModel.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.ComponentModel; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.MoveToNamespace { internal class MoveToNamespaceDialogViewModel : AbstractNotifyPropertyChanged, IDataErrorInfo { private readonly ISyntaxFacts _syntaxFacts; public MoveToNamespaceDialogViewModel( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFacts, ImmutableArray<string> namespaceHistory) { _syntaxFacts = syntaxFacts ?? throw new ArgumentNullException(nameof(syntaxFacts)); _namespaceName = defaultNamespace; AvailableNamespaces = namespaceHistory.Select(n => new NamespaceItem(true, n)) .Concat(availableNamespaces.Except(namespaceHistory).Select(n => new NamespaceItem(false, n))) .ToImmutableArray(); PropertyChanged += MoveToNamespaceDialogViewModel_PropertyChanged; } private void MoveToNamespaceDialogViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(NamespaceName): OnNamespaceUpdated(); break; } } public void OnNamespaceUpdated() { var isNewNamespace = !AvailableNamespaces.Any(i => i.Namespace == NamespaceName); var isValidName = !isNewNamespace || IsValidNamespace(NamespaceName); if (isNewNamespace && isValidName) { Icon = KnownMonikers.StatusInformation; Message = ServicesVSResources.A_new_namespace_will_be_created; ShowMessage = true; CanSubmit = true; } else if (!isValidName) { Icon = KnownMonikers.StatusInvalid; Message = ServicesVSResources.This_is_an_invalid_namespace; ShowMessage = true; CanSubmit = false; } else { ShowMessage = false; CanSubmit = true; } } private bool IsValidNamespace(string namespaceName) { if (string.IsNullOrEmpty(namespaceName)) { return false; } foreach (var identifier in namespaceName.Split('.')) { if (_syntaxFacts.IsValidIdentifier(identifier)) { continue; } return false; } return true; } private string _namespaceName; public string NamespaceName { get => _namespaceName; set => SetProperty(ref _namespaceName, value); } public ImmutableArray<NamespaceItem> AvailableNamespaces { get; } private ImageMoniker _icon; public ImageMoniker Icon { get => _icon; private set => SetProperty(ref _icon, value); } private string? _message; public string? Message { get => _message; private set => SetProperty(ref _message, value); } private bool _showMessage = false; public bool ShowMessage { get => _showMessage; private set => SetProperty(ref _showMessage, value); } private bool _canSubmit = true; public bool CanSubmit { get => _canSubmit; private set => SetProperty(ref _canSubmit, value); } public string Error => CanSubmit ? string.Empty : Message ?? string.Empty; public string this[string columnName] => columnName switch { nameof(NamespaceName) => Error, _ => string.Empty }; } }
// 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.ComponentModel; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.MoveToNamespace { internal class MoveToNamespaceDialogViewModel : AbstractNotifyPropertyChanged, IDataErrorInfo { private readonly ISyntaxFacts _syntaxFacts; public MoveToNamespaceDialogViewModel( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFacts, ImmutableArray<string> namespaceHistory) { _syntaxFacts = syntaxFacts ?? throw new ArgumentNullException(nameof(syntaxFacts)); _namespaceName = defaultNamespace; AvailableNamespaces = namespaceHistory.Select(n => new NamespaceItem(true, n)) .Concat(availableNamespaces.Except(namespaceHistory).Select(n => new NamespaceItem(false, n))) .ToImmutableArray(); PropertyChanged += MoveToNamespaceDialogViewModel_PropertyChanged; } private void MoveToNamespaceDialogViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(NamespaceName): OnNamespaceUpdated(); break; } } public void OnNamespaceUpdated() { var isNewNamespace = !AvailableNamespaces.Any(i => i.Namespace == NamespaceName); var isValidName = !isNewNamespace || IsValidNamespace(NamespaceName); if (isNewNamespace && isValidName) { Icon = KnownMonikers.StatusInformation; Message = ServicesVSResources.A_new_namespace_will_be_created; ShowMessage = true; CanSubmit = true; } else if (!isValidName) { Icon = KnownMonikers.StatusInvalid; Message = ServicesVSResources.This_is_an_invalid_namespace; ShowMessage = true; CanSubmit = false; } else { ShowMessage = false; CanSubmit = true; } } private bool IsValidNamespace(string namespaceName) { if (string.IsNullOrEmpty(namespaceName)) { return false; } foreach (var identifier in namespaceName.Split('.')) { if (_syntaxFacts.IsValidIdentifier(identifier)) { continue; } return false; } return true; } private string _namespaceName; public string NamespaceName { get => _namespaceName; set => SetProperty(ref _namespaceName, value); } public ImmutableArray<NamespaceItem> AvailableNamespaces { get; } private ImageMoniker _icon; public ImageMoniker Icon { get => _icon; private set => SetProperty(ref _icon, value); } private string? _message; public string? Message { get => _message; private set => SetProperty(ref _message, value); } private bool _showMessage = false; public bool ShowMessage { get => _showMessage; private set => SetProperty(ref _showMessage, value); } private bool _canSubmit = true; public bool CanSubmit { get => _canSubmit; private set => SetProperty(ref _canSubmit, value); } public string Error => CanSubmit ? string.Empty : Message ?? string.Empty; public string this[string columnName] => columnName switch { nameof(NamespaceName) => Error, _ => string.Empty }; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/Core/Test/Utilities/VsNavInfoHelpers.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.CompilerServices Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Utilities.VsNavInfo Friend Module VsNavInfoHelpers Public Sub IsOK(result As Integer) Assert.Equal(VSConstants.S_OK, result) End Sub Public Delegate Sub NodeVerifier(vsNavInfoNode As IVsNavInfoNode) Private Function Node(expectedListType As _LIB_LISTTYPE, expectedName As String) As NodeVerifier Return Sub(vsNavInfoNode) Dim listType As UInteger IsOK(vsNavInfoNode.get_Type(listType)) Assert.Equal(CUInt(expectedListType), listType) Dim actualName As String = Nothing IsOK(vsNavInfoNode.get_Name(actualName)) Assert.Equal(expectedName, actualName) End Sub End Function Public Function Package(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_PACKAGE, expectedName) End Function Public Function [Namespace](expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_NAMESPACES, expectedName) End Function Public Function [Class](expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_CLASSES, expectedName) End Function Public Function Member(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_MEMBERS, expectedName) End Function Public Function Hierarchy(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_HIERARCHY, expectedName) End Function <Extension> Public Sub VerifyNodes(enumerator As IVsEnumNavInfoNodes, verifiers() As NodeVerifier) Dim index = 0 Dim actualNode = New IVsNavInfoNode(0) {} Dim fetched As UInteger While enumerator.Next(1, actualNode, fetched) = VSConstants.S_OK Assert.True(index < verifiers.Length) Dim verifier = verifiers(index) index += 1 verifier(actualNode(0)) End While End Sub 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. Imports System.Runtime.CompilerServices Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Utilities.VsNavInfo Friend Module VsNavInfoHelpers Public Sub IsOK(result As Integer) Assert.Equal(VSConstants.S_OK, result) End Sub Public Delegate Sub NodeVerifier(vsNavInfoNode As IVsNavInfoNode) Private Function Node(expectedListType As _LIB_LISTTYPE, expectedName As String) As NodeVerifier Return Sub(vsNavInfoNode) Dim listType As UInteger IsOK(vsNavInfoNode.get_Type(listType)) Assert.Equal(CUInt(expectedListType), listType) Dim actualName As String = Nothing IsOK(vsNavInfoNode.get_Name(actualName)) Assert.Equal(expectedName, actualName) End Sub End Function Public Function Package(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_PACKAGE, expectedName) End Function Public Function [Namespace](expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_NAMESPACES, expectedName) End Function Public Function [Class](expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_CLASSES, expectedName) End Function Public Function Member(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_MEMBERS, expectedName) End Function Public Function Hierarchy(expectedName As String) As NodeVerifier Return Node(_LIB_LISTTYPE.LLT_HIERARCHY, expectedName) End Function <Extension> Public Sub VerifyNodes(enumerator As IVsEnumNavInfoNodes, verifiers() As NodeVerifier) Dim index = 0 Dim actualNode = New IVsNavInfoNode(0) {} Dim fetched As UInteger While enumerator.Next(1, actualNode, fetched) = VSConstants.S_OK Assert.True(index < verifiers.Length) Dim verifier = verifiers(index) index += 1 verifier(actualNode(0)) End While End Sub End Module End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/CSharp/Portable/Binder/SimpleProgramBinder.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder owns the scope for Simple Program top-level statements. /// </summary> internal sealed class SimpleProgramBinder : LocalScopeBinder { private readonly SynthesizedSimpleProgramEntryPointSymbol _entryPoint; public SimpleProgramBinder(Binder enclosing, SynthesizedSimpleProgramEntryPointSymbol entryPoint) : base(enclosing, enclosing.Flags) { _entryPoint = entryPoint; } protected override ImmutableArray<LocalSymbol> BuildLocals() { ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { this.BuildLocals(this, topLevelStatement.Statement, locals); } } return locals.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { ArrayBuilder<LocalFunctionSymbol>? locals = null; foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { this.BuildLocalFunctions(topLevelStatement.Statement, ref locals); } } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { ArrayBuilder<LabelSymbol>? labels = null; foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { BuildLabels(_entryPoint, topLevelStatement.Statement, ref labels); } } return labels?.ToImmutableAndFree() ?? ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return true; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _entryPoint.SyntaxNode; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } } }
// 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This binder owns the scope for Simple Program top-level statements. /// </summary> internal sealed class SimpleProgramBinder : LocalScopeBinder { private readonly SynthesizedSimpleProgramEntryPointSymbol _entryPoint; public SimpleProgramBinder(Binder enclosing, SynthesizedSimpleProgramEntryPointSymbol entryPoint) : base(enclosing, enclosing.Flags) { _entryPoint = entryPoint; } protected override ImmutableArray<LocalSymbol> BuildLocals() { ArrayBuilder<LocalSymbol> locals = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { this.BuildLocals(this, topLevelStatement.Statement, locals); } } return locals.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { ArrayBuilder<LocalFunctionSymbol>? locals = null; foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { this.BuildLocalFunctions(topLevelStatement.Statement, ref locals); } } return locals?.ToImmutableAndFree() ?? ImmutableArray<LocalFunctionSymbol>.Empty; } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { ArrayBuilder<LabelSymbol>? labels = null; foreach (var statement in _entryPoint.CompilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { BuildLabels(_entryPoint, topLevelStatement.Statement, ref labels); } } return labels?.ToImmutableAndFree() ?? ImmutableArray<LabelSymbol>.Empty; } internal override bool IsLabelsScopeBinder { get { return true; } } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return _entryPoint.SyntaxNode; } } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (ScopeDesignator == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.RequestTelemetryLogger.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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { /// <summary> /// Logs metadata on LSP requests (duration, success / failure metrics) /// for this particular LSP server instance. /// </summary> internal class RequestTelemetryLogger : IDisposable { private const string QueuedDurationKey = "QueuedDuration"; private readonly string _serverTypeName; /// <summary> /// Histogram to aggregate the time in queue metrics. /// </summary> private HistogramLogAggregator? _queuedDurationLogAggregator; /// <summary> /// Histogram to aggregate total request duration metrics. /// This histogram is log based as request latencies can be highly variable depending /// on the request being handled. As such, we apply the log based function /// defined by ComputeLogValue to the request latencies for storing in the histogram. /// This provides highly detailed buckets when duration is in MS, but less detailed /// when the duration is in terms of seconds or minutes. /// </summary> private HistogramLogAggregator? _requestDurationLogAggregator; /// <summary> /// Store request counters in a concurrent dictionary as non-mutating LSP requests can /// run alongside other non-mutating requests. /// </summary> private readonly ConcurrentDictionary<string, Counter> _requestCounters; private readonly LogAggregator _findDocumentResults; public RequestTelemetryLogger(string serverTypeName) { _serverTypeName = serverTypeName; _requestCounters = new(); _findDocumentResults = new(); // Buckets queued duration into 10ms buckets with the last bucket starting at 1000ms. // Queue times are relatively short and fall under 50ms, so tracking past 1000ms is not useful. _queuedDurationLogAggregator = new HistogramLogAggregator(bucketSize: 10, maxBucketValue: 1000); // Since this is a log based histogram, these are appropriate bucket sizes for the log data. // A bucket at 1 corresponds to ~26ms, while the max bucket value corresponds to ~17minutes _requestDurationLogAggregator = new HistogramLogAggregator(bucketSize: 1, maxBucketValue: 40); } public void UpdateFindDocumentTelemetryData(bool success, string? workspaceKind) { var workspaceKindTelemetryProperty = success ? workspaceKind : "Failed"; if (workspaceKindTelemetryProperty != null) { _findDocumentResults.IncreaseCount(workspaceKindTelemetryProperty); } } public void UpdateTelemetryData( string methodName, TimeSpan queuedDuration, TimeSpan requestDuration, Result result) { // Find the bucket corresponding to the queued duration and update the count of durations in that bucket. // This is not broken down per method as time in queue is not specific to an LSP method. _queuedDurationLogAggregator?.IncreaseCount(QueuedDurationKey, Convert.ToDecimal(queuedDuration.TotalMilliseconds)); // Store the request time metrics per LSP method. _requestDurationLogAggregator?.IncreaseCount(methodName, Convert.ToDecimal(ComputeLogValue(requestDuration.TotalMilliseconds))); _requestCounters.GetOrAdd(methodName, (_) => new Counter()).IncrementCount(result); } /// <summary> /// Given an input duration in MS, this transforms it using /// the log function below to put in reasonable log based buckets /// from 50ms to 1 hour. Similar transformations must be done to read /// the data from kusto. /// </summary> private static double ComputeLogValue(double durationInMS) { return 10d * Math.Log10((durationInMS / 100d) + 1); } /// <summary> /// Only output aggregate telemetry to the vs logger when the server instance is disposed /// to avoid spamming the telemetry output with thousands of events /// </summary> public void Dispose() { if (_queuedDurationLogAggregator is null || _queuedDurationLogAggregator.IsEmpty || _requestDurationLogAggregator is null || _requestDurationLogAggregator.IsEmpty) { return; } var queuedDurationCounter = _queuedDurationLogAggregator.GetValue(QueuedDurationKey); Logger.Log(FunctionId.LSP_TimeInQueue, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["bucketsize_ms"] = queuedDurationCounter?.BucketSize; m["maxbucketvalue_ms"] = queuedDurationCounter?.MaxBucketValue; m["buckets"] = queuedDurationCounter?.GetBucketsAsString(); })); foreach (var kvp in _requestCounters) { Logger.Log(FunctionId.LSP_RequestCounter, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["method"] = kvp.Key; m["successful"] = kvp.Value.SucceededCount; m["failed"] = kvp.Value.FailedCount; m["cancelled"] = kvp.Value.CancelledCount; })); var requestExecutionDuration = _requestDurationLogAggregator.GetValue(kvp.Key); Logger.Log(FunctionId.LSP_RequestDuration, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["method"] = kvp.Key; m["bucketsize_logms"] = requestExecutionDuration?.BucketSize; m["maxbucketvalue_logms"] = requestExecutionDuration?.MaxBucketValue; m["bucketdata_logms"] = requestExecutionDuration?.GetBucketsAsString(); })); } Logger.Log(FunctionId.LSP_FindDocumentInWorkspace, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; foreach (var kvp in _findDocumentResults) { var info = kvp.Key.ToString(); m[info] = kvp.Value.GetCount(); } })); // Clear telemetry we've published in case dispose is called multiple times. _requestCounters.Clear(); _queuedDurationLogAggregator = null; _requestDurationLogAggregator = null; } private class Counter { private int _succeededCount; private int _failedCount; private int _cancelledCount; public int SucceededCount => _succeededCount; public int FailedCount => _failedCount; public int CancelledCount => _cancelledCount; public void IncrementCount(Result result) { switch (result) { case Result.Succeeded: Interlocked.Increment(ref _succeededCount); break; case Result.Failed: Interlocked.Increment(ref _failedCount); break; case Result.Cancelled: Interlocked.Increment(ref _cancelledCount); break; } } } internal enum Result { Succeeded, Failed, Cancelled } } } }
// 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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { /// <summary> /// Logs metadata on LSP requests (duration, success / failure metrics) /// for this particular LSP server instance. /// </summary> internal class RequestTelemetryLogger : IDisposable { private const string QueuedDurationKey = "QueuedDuration"; private readonly string _serverTypeName; /// <summary> /// Histogram to aggregate the time in queue metrics. /// </summary> private HistogramLogAggregator? _queuedDurationLogAggregator; /// <summary> /// Histogram to aggregate total request duration metrics. /// This histogram is log based as request latencies can be highly variable depending /// on the request being handled. As such, we apply the log based function /// defined by ComputeLogValue to the request latencies for storing in the histogram. /// This provides highly detailed buckets when duration is in MS, but less detailed /// when the duration is in terms of seconds or minutes. /// </summary> private HistogramLogAggregator? _requestDurationLogAggregator; /// <summary> /// Store request counters in a concurrent dictionary as non-mutating LSP requests can /// run alongside other non-mutating requests. /// </summary> private readonly ConcurrentDictionary<string, Counter> _requestCounters; private readonly LogAggregator _findDocumentResults; public RequestTelemetryLogger(string serverTypeName) { _serverTypeName = serverTypeName; _requestCounters = new(); _findDocumentResults = new(); // Buckets queued duration into 10ms buckets with the last bucket starting at 1000ms. // Queue times are relatively short and fall under 50ms, so tracking past 1000ms is not useful. _queuedDurationLogAggregator = new HistogramLogAggregator(bucketSize: 10, maxBucketValue: 1000); // Since this is a log based histogram, these are appropriate bucket sizes for the log data. // A bucket at 1 corresponds to ~26ms, while the max bucket value corresponds to ~17minutes _requestDurationLogAggregator = new HistogramLogAggregator(bucketSize: 1, maxBucketValue: 40); } public void UpdateFindDocumentTelemetryData(bool success, string? workspaceKind) { var workspaceKindTelemetryProperty = success ? workspaceKind : "Failed"; if (workspaceKindTelemetryProperty != null) { _findDocumentResults.IncreaseCount(workspaceKindTelemetryProperty); } } public void UpdateTelemetryData( string methodName, TimeSpan queuedDuration, TimeSpan requestDuration, Result result) { // Find the bucket corresponding to the queued duration and update the count of durations in that bucket. // This is not broken down per method as time in queue is not specific to an LSP method. _queuedDurationLogAggregator?.IncreaseCount(QueuedDurationKey, Convert.ToDecimal(queuedDuration.TotalMilliseconds)); // Store the request time metrics per LSP method. _requestDurationLogAggregator?.IncreaseCount(methodName, Convert.ToDecimal(ComputeLogValue(requestDuration.TotalMilliseconds))); _requestCounters.GetOrAdd(methodName, (_) => new Counter()).IncrementCount(result); } /// <summary> /// Given an input duration in MS, this transforms it using /// the log function below to put in reasonable log based buckets /// from 50ms to 1 hour. Similar transformations must be done to read /// the data from kusto. /// </summary> private static double ComputeLogValue(double durationInMS) { return 10d * Math.Log10((durationInMS / 100d) + 1); } /// <summary> /// Only output aggregate telemetry to the vs logger when the server instance is disposed /// to avoid spamming the telemetry output with thousands of events /// </summary> public void Dispose() { if (_queuedDurationLogAggregator is null || _queuedDurationLogAggregator.IsEmpty || _requestDurationLogAggregator is null || _requestDurationLogAggregator.IsEmpty) { return; } var queuedDurationCounter = _queuedDurationLogAggregator.GetValue(QueuedDurationKey); Logger.Log(FunctionId.LSP_TimeInQueue, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["bucketsize_ms"] = queuedDurationCounter?.BucketSize; m["maxbucketvalue_ms"] = queuedDurationCounter?.MaxBucketValue; m["buckets"] = queuedDurationCounter?.GetBucketsAsString(); })); foreach (var kvp in _requestCounters) { Logger.Log(FunctionId.LSP_RequestCounter, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["method"] = kvp.Key; m["successful"] = kvp.Value.SucceededCount; m["failed"] = kvp.Value.FailedCount; m["cancelled"] = kvp.Value.CancelledCount; })); var requestExecutionDuration = _requestDurationLogAggregator.GetValue(kvp.Key); Logger.Log(FunctionId.LSP_RequestDuration, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; m["method"] = kvp.Key; m["bucketsize_logms"] = requestExecutionDuration?.BucketSize; m["maxbucketvalue_logms"] = requestExecutionDuration?.MaxBucketValue; m["bucketdata_logms"] = requestExecutionDuration?.GetBucketsAsString(); })); } Logger.Log(FunctionId.LSP_FindDocumentInWorkspace, KeyValueLogMessage.Create(LogType.Trace, m => { m["server"] = _serverTypeName; foreach (var kvp in _findDocumentResults) { var info = kvp.Key.ToString(); m[info] = kvp.Value.GetCount(); } })); // Clear telemetry we've published in case dispose is called multiple times. _requestCounters.Clear(); _queuedDurationLogAggregator = null; _requestDurationLogAggregator = null; } private class Counter { private int _succeededCount; private int _failedCount; private int _cancelledCount; public int SucceededCount => _succeededCount; public int FailedCount => _failedCount; public int CancelledCount => _cancelledCount; public void IncrementCount(Result result) { switch (result) { case Result.Succeeded: Interlocked.Increment(ref _succeededCount); break; case Result.Failed: Interlocked.Increment(ref _failedCount); break; case Result.Cancelled: Interlocked.Increment(ref _cancelledCount); break; } } } internal enum Result { Succeeded, Failed, Cancelled } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/Workspace/DocumentActiveContextChangedEventArgs.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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public sealed class DocumentActiveContextChangedEventArgs : EventArgs { public Solution Solution { get; } public SourceTextContainer SourceTextContainer { get; } public DocumentId OldActiveContextDocumentId { get; } public DocumentId NewActiveContextDocumentId { get; } public DocumentActiveContextChangedEventArgs(Solution solution, SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(sourceTextContainer); Contract.ThrowIfNull(oldActiveContextDocumentId); Contract.ThrowIfNull(newActiveContextDocumentId); this.Solution = solution; this.SourceTextContainer = sourceTextContainer; this.OldActiveContextDocumentId = oldActiveContextDocumentId; this.NewActiveContextDocumentId = newActiveContextDocumentId; } } }
// 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public sealed class DocumentActiveContextChangedEventArgs : EventArgs { public Solution Solution { get; } public SourceTextContainer SourceTextContainer { get; } public DocumentId OldActiveContextDocumentId { get; } public DocumentId NewActiveContextDocumentId { get; } public DocumentActiveContextChangedEventArgs(Solution solution, SourceTextContainer sourceTextContainer, DocumentId oldActiveContextDocumentId, DocumentId newActiveContextDocumentId) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(sourceTextContainer); Contract.ThrowIfNull(oldActiveContextDocumentId); Contract.ThrowIfNull(newActiveContextDocumentId); this.Solution = solution; this.SourceTextContainer = sourceTextContainer; this.OldActiveContextDocumentId = oldActiveContextDocumentId; this.NewActiveContextDocumentId = newActiveContextDocumentId; } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/CoreTest/WorkspaceTests/GeneralWorkspaceTests.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.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; using System; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class GeneralWorkspaceTests { [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentContent_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); var changedDoc = originalDoc.WithText(SourceText.From("new")); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_documents_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentName_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal("TestDocument", originalDoc.Name); var newName = "ChangedName"; var changedDoc = originalDoc.WithName(newName); Assert.Equal(newName, changedDoc.Name); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentFolders_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal(0, originalDoc.Folders.Count); var changedDoc = originalDoc.WithFolders(new[] { "A", "B" }); Assert.Equal(2, changedDoc.Folders.Count); Assert.Equal("A", changedDoc.Folders[0]); Assert.Equal("B", changedDoc.Folders[1]); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentFilePath_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Null(originalDoc.FilePath); var newPath = @"\goo\TestDocument.cs"; var changedDoc = originalDoc.WithFilePath(newPath); Assert.Equal(newPath, changedDoc.FilePath); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentSourceCodeKind_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal(SourceCodeKind.Regular, originalDoc.SourceCodeKind); var changedDoc = originalDoc.WithSourceCodeKind(SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, changedDoc.SourceCodeKind); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } private class NoChangesAllowedWorkspace : Workspace { public NoChangesAllowedWorkspace(HostServices services, string workspaceKind = "Custom") : base(services, workspaceKind) { } public NoChangesAllowedWorkspace() : this(Host.Mef.MefHostServices.DefaultHost) { } public override bool CanApplyChange(ApplyChangesKind feature) => false; public Project AddProject(string name, string language) { var info = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), name, name, language); return this.AddProject(info); } public Project AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } this.OnProjectAdded(projectInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projectInfo.Id); } public Document AddDocument(ProjectId projectId, string name, SourceText text) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } var id = DocumentId.CreateNewId(projectId); var loader = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())); return this.AddDocument(DocumentInfo.Create(id, name, loader: loader)); } /// <summary> /// Adds a document to the workspace. /// </summary> public Document AddDocument(DocumentInfo documentInfo) { if (documentInfo == null) { throw new ArgumentNullException(nameof(documentInfo)); } this.OnDocumentAdded(documentInfo); return this.CurrentSolution.GetDocument(documentInfo.Id); } } } }
// 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.Host; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; using System; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public class GeneralWorkspaceTests { [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentContent_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); var changedDoc = originalDoc.WithText(SourceText.From("new")); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_documents_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentName_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal("TestDocument", originalDoc.Name); var newName = "ChangedName"; var changedDoc = originalDoc.WithName(newName); Assert.Equal(newName, changedDoc.Name); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentFolders_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal(0, originalDoc.Folders.Count); var changedDoc = originalDoc.WithFolders(new[] { "A", "B" }); Assert.Equal(2, changedDoc.Folders.Count); Assert.Equal("A", changedDoc.Folders[0]); Assert.Equal("B", changedDoc.Folders[1]); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentFilePath_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Null(originalDoc.FilePath); var newPath = @"\goo\TestDocument.cs"; var changedDoc = originalDoc.WithFilePath(newPath); Assert.Equal(newPath, changedDoc.FilePath); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestChangeDocumentSourceCodeKind_TryApplyChanges_Throws() { using var ws = new NoChangesAllowedWorkspace(); var projectId = ws.AddProject("TestProject", LanguageNames.CSharp).Id; var originalDoc = ws.AddDocument(projectId, "TestDocument", SourceText.From("")); Assert.Equal(SourceCodeKind.Regular, originalDoc.SourceCodeKind); var changedDoc = originalDoc.WithSourceCodeKind(SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, changedDoc.SourceCodeKind); NotSupportedException e = null; try { ws.TryApplyChanges(changedDoc.Project.Solution); } catch (NotSupportedException x) { e = x; } Assert.NotNull(e); Assert.Equal(WorkspacesResources.Changing_document_property_is_not_supported, e.Message); } private class NoChangesAllowedWorkspace : Workspace { public NoChangesAllowedWorkspace(HostServices services, string workspaceKind = "Custom") : base(services, workspaceKind) { } public NoChangesAllowedWorkspace() : this(Host.Mef.MefHostServices.DefaultHost) { } public override bool CanApplyChange(ApplyChangesKind feature) => false; public Project AddProject(string name, string language) { var info = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), name, name, language); return this.AddProject(info); } public Project AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } this.OnProjectAdded(projectInfo); this.UpdateReferencesAfterAdd(); return this.CurrentSolution.GetProject(projectInfo.Id); } public Document AddDocument(ProjectId projectId, string name, SourceText text) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } if (text == null) { throw new ArgumentNullException(nameof(text)); } var id = DocumentId.CreateNewId(projectId); var loader = TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())); return this.AddDocument(DocumentInfo.Create(id, name, loader: loader)); } /// <summary> /// Adds a document to the workspace. /// </summary> public Document AddDocument(DocumentInfo documentInfo) { if (documentInfo == null) { throw new ArgumentNullException(nameof(documentInfo)); } this.OnDocumentAdded(documentInfo); return this.CurrentSolution.GetDocument(documentInfo.Id); } } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceAnalysisResult.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; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal partial class MoveToNamespaceAnalysisResult { public static readonly MoveToNamespaceAnalysisResult Invalid = new(); public bool CanPerform { get; } public Document Document { get; } public SyntaxNode SyntaxNode { get; } public string OriginalNamespace { get; } public ContainerType Container { get; } public ImmutableArray<string> Namespaces { get; } public MoveToNamespaceAnalysisResult( Document document, SyntaxNode syntaxNode, string originalNamespace, ImmutableArray<string> namespaces, ContainerType container) { CanPerform = true; Document = document; SyntaxNode = syntaxNode; OriginalNamespace = originalNamespace; Container = container; Namespaces = namespaces; } private MoveToNamespaceAnalysisResult() => CanPerform = 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.Collections.Immutable; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal partial class MoveToNamespaceAnalysisResult { public static readonly MoveToNamespaceAnalysisResult Invalid = new(); public bool CanPerform { get; } public Document Document { get; } public SyntaxNode SyntaxNode { get; } public string OriginalNamespace { get; } public ContainerType Container { get; } public ImmutableArray<string> Namespaces { get; } public MoveToNamespaceAnalysisResult( Document document, SyntaxNode syntaxNode, string originalNamespace, ImmutableArray<string> namespaces, ContainerType container) { CanPerform = true; Document = document; SyntaxNode = syntaxNode; OriginalNamespace = originalNamespace; Container = container; Namespaces = namespaces; } private MoveToNamespaceAnalysisResult() => CanPerform = false; } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/VisualStudio/CSharp/Impl/Interactive/CSharpVsInteractiveWindowProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using LanguageServiceGuids = Microsoft.VisualStudio.LanguageServices.Guids; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [Export(typeof(CSharpVsInteractiveWindowProvider))] internal sealed class CSharpVsInteractiveWindowProvider : VsInteractiveWindowProvider { private readonly IThreadingContext _threadingContext; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsInteractiveWindowProvider( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IAsynchronousOperationListenerProvider listenerProvider, IVsInteractiveWindowFactory interactiveWindowFactory, IViewClassifierAggregatorService classifierAggregator, IContentTypeRegistryService contentTypeRegistry, IInteractiveWindowCommandsFactory commandsFactory, [ImportMany] IInteractiveWindowCommand[] commands, VisualStudioWorkspace workspace) : base(serviceProvider, interactiveWindowFactory, classifierAggregator, contentTypeRegistry, commandsFactory, commands, workspace) { _threadingContext = threadingContext; _listener = listenerProvider.GetListener(FeatureAttribute.InteractiveEvaluator); } protected override Guid LanguageServiceGuid => LanguageServiceGuids.CSharpLanguageServiceId; protected override Guid Id => CSharpVsInteractiveWindowPackage.Id; // Note: intentionally left unlocalized (we treat these words as if they were unregistered trademarks) protected override string Title => "C# Interactive"; protected override FunctionId InteractiveWindowFunctionId => FunctionId.CSharp_Interactive_Window; protected override CSharpInteractiveEvaluator CreateInteractiveEvaluator( SVsServiceProvider serviceProvider, IViewClassifierAggregatorService classifierAggregator, IContentTypeRegistryService contentTypeRegistry, VisualStudioWorkspace workspace) { return new CSharpInteractiveEvaluator( _threadingContext, _listener, contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType), workspace.Services.HostServices, classifierAggregator, CommandsFactory, Commands, CSharpInteractiveEvaluatorLanguageInfoProvider.Instance, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } } }
// 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using LanguageServiceGuids = Microsoft.VisualStudio.LanguageServices.Guids; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Interactive { [Export(typeof(CSharpVsInteractiveWindowProvider))] internal sealed class CSharpVsInteractiveWindowProvider : VsInteractiveWindowProvider { private readonly IThreadingContext _threadingContext; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVsInteractiveWindowProvider( IThreadingContext threadingContext, SVsServiceProvider serviceProvider, IAsynchronousOperationListenerProvider listenerProvider, IVsInteractiveWindowFactory interactiveWindowFactory, IViewClassifierAggregatorService classifierAggregator, IContentTypeRegistryService contentTypeRegistry, IInteractiveWindowCommandsFactory commandsFactory, [ImportMany] IInteractiveWindowCommand[] commands, VisualStudioWorkspace workspace) : base(serviceProvider, interactiveWindowFactory, classifierAggregator, contentTypeRegistry, commandsFactory, commands, workspace) { _threadingContext = threadingContext; _listener = listenerProvider.GetListener(FeatureAttribute.InteractiveEvaluator); } protected override Guid LanguageServiceGuid => LanguageServiceGuids.CSharpLanguageServiceId; protected override Guid Id => CSharpVsInteractiveWindowPackage.Id; // Note: intentionally left unlocalized (we treat these words as if they were unregistered trademarks) protected override string Title => "C# Interactive"; protected override FunctionId InteractiveWindowFunctionId => FunctionId.CSharp_Interactive_Window; protected override CSharpInteractiveEvaluator CreateInteractiveEvaluator( SVsServiceProvider serviceProvider, IViewClassifierAggregatorService classifierAggregator, IContentTypeRegistryService contentTypeRegistry, VisualStudioWorkspace workspace) { return new CSharpInteractiveEvaluator( _threadingContext, _listener, contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType), workspace.Services.HostServices, classifierAggregator, CommandsFactory, Commands, CSharpInteractiveEvaluatorLanguageInfoProvider.Instance, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Core/Portable/Wrapping/Edit.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.PooledObjects; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Represents an edit between two tokens. Specifically, provides the new trailing trivia for /// the <see cref="Left"/> token and the new leading trivia for the <see /// cref="Right"/> token. /// </summary> internal readonly struct Edit { public readonly SyntaxToken Left; public readonly SyntaxToken Right; public readonly SyntaxTriviaList NewLeftTrailingTrivia; public readonly SyntaxTriviaList NewRightLeadingTrivia; private Edit( SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia, SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia) { Left = left; Right = right; NewLeftTrailingTrivia = newLeftTrailingTrivia; NewRightLeadingTrivia = newRightLeadingTrivia; } public string GetNewTrivia() { var result = PooledStringBuilder.GetInstance(); AppendTrivia(result, NewLeftTrailingTrivia); AppendTrivia(result, NewRightLeadingTrivia); return result.ToStringAndFree(); } private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { result.Builder.Append(trivia.ToFullString()); } } /// <summary> /// Create the Edit representing the deletion of all trivia between left and right. /// </summary> public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right) => UpdateBetween(left, default, default(SyntaxTriviaList), right); public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right) { return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right); } public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right) { var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken(); var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken(); return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia); } } }
// 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.PooledObjects; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Represents an edit between two tokens. Specifically, provides the new trailing trivia for /// the <see cref="Left"/> token and the new leading trivia for the <see /// cref="Right"/> token. /// </summary> internal readonly struct Edit { public readonly SyntaxToken Left; public readonly SyntaxToken Right; public readonly SyntaxTriviaList NewLeftTrailingTrivia; public readonly SyntaxTriviaList NewRightLeadingTrivia; private Edit( SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia, SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia) { Left = left; Right = right; NewLeftTrailingTrivia = newLeftTrailingTrivia; NewRightLeadingTrivia = newRightLeadingTrivia; } public string GetNewTrivia() { var result = PooledStringBuilder.GetInstance(); AppendTrivia(result, NewLeftTrailingTrivia); AppendTrivia(result, NewRightLeadingTrivia); return result.ToStringAndFree(); } private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { result.Builder.Append(trivia.ToFullString()); } } /// <summary> /// Create the Edit representing the deletion of all trivia between left and right. /// </summary> public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right) => UpdateBetween(left, default, default(SyntaxTriviaList), right); public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right) { return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right); } public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right) { var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken(); var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken(); return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Features/Lsif/Generator/Writing/ILsifJsonWriter.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 Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal interface ILsifJsonWriter { void Write(Element element); void WriteAll(List<Element> elements); } }
// 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 Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { internal interface ILsifJsonWriter { void Write(Element element); void WriteAll(List<Element> elements); } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ComClassTests.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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ComClassTests Inherits BasicTestBase Private Function ReflectComClass( pm As PEModuleSymbol, comClassName As String, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing ) As XElement Dim type As PENamedTypeSymbol = DirectCast(pm.ContainingAssembly.GetTypeByMetadataName(comClassName), PENamedTypeSymbol) Dim combinedFilter = Function(m As Symbol) Return (memberFilter Is Nothing OrElse memberFilter(m)) AndAlso (m.ContainingSymbol IsNot type OrElse m.Kind <> SymbolKind.NamedType OrElse Not DirectCast(m, NamedTypeSymbol).IsDelegateType()) End Function Return ReflectType(type, combinedFilter) End Function Private Function ReflectType(type As PENamedTypeSymbol, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing) As XElement Dim result = <<%= type.TypeKind.ToString() %> Name=<%= type.Name %>></> Dim typeDefFlags = New StringBuilder() MetadataSignatureHelper.AppendTypeAttributes(typeDefFlags, type.TypeDefFlags) result.Add(<TypeDefFlags><%= typeDefFlags %></TypeDefFlags>) If type.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(type.GetAttributes())) End If For Each [interface] In type.Interfaces result.Add(<Implements><%= [interface].ToTestDisplayString() %></Implements>) Next For Each member In type.GetMembers If memberFilter IsNot Nothing AndAlso Not memberFilter(member) Then Continue For End If Select Case member.Kind Case SymbolKind.NamedType result.Add(ReflectType(DirectCast(member, PENamedTypeSymbol), memberFilter)) Case SymbolKind.Method result.Add(ReflectMethod(DirectCast(member, PEMethodSymbol))) Case SymbolKind.Property result.Add(ReflectProperty(DirectCast(member, PEPropertySymbol))) Case SymbolKind.Event result.Add(ReflectEvent(DirectCast(member, PEEventSymbol))) Case SymbolKind.Field result.Add(ReflectField(DirectCast(member, PEFieldSymbol))) Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Kind) End Select Next Return result End Function Private Function ReflectAttributes(attrData As ImmutableArray(Of VisualBasicAttributeData)) As XElement Dim result = <Attributes></Attributes> For Each attr In attrData Dim application = <<%= attr.AttributeClass.ToTestDisplayString() %>/> result.Add(application) application.Add(<ctor><%= attr.AttributeConstructor.ToTestDisplayString() %></ctor>) For Each arg In attr.CommonConstructorArguments application.Add(<a><%= arg.Value.ToString() %></a>) Next For Each named In attr.CommonNamedArguments application.Add(<Named Name=<%= named.Key %>><%= named.Value.Value.ToString() %></Named>) Next Next Return result End Function Private Function ReflectMethod(m As PEMethodSymbol) As XElement Dim result = <Method Name=<%= m.Name %> CallingConvention=<%= m.CallingConvention %>/> Dim methodFlags = New StringBuilder() Dim methodImplFlags = New StringBuilder() MetadataSignatureHelper.AppendMethodAttributes(methodFlags, m.MethodFlags) MetadataSignatureHelper.AppendMethodImplAttributes(methodImplFlags, m.MethodImplFlags) result.Add(<MethodFlags><%= methodFlags %></MethodFlags>) result.Add(<MethodImplFlags><%= methodImplFlags %></MethodImplFlags>) If m.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(m.GetAttributes())) End If For Each impl In m.ExplicitInterfaceImplementations result.Add(<Implements><%= impl.ToTestDisplayString() %></Implements>) Next For Each param In m.Parameters result.Add(ReflectParameter(DirectCast(param, PEParameterSymbol))) Next Dim ret = <Return><Type><%= m.ReturnType %></Type></Return> result.Add(ret) Dim retFlags = m.ReturnParam.ParamFlags If retFlags <> 0 Then Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, retFlags) ret.Add(<ParamFlags><%= paramFlags %></ParamFlags>) End If If m.GetReturnTypeAttributes().Length > 0 Then ret.Add(ReflectAttributes(m.GetReturnTypeAttributes())) End If Return result End Function Private Function ReflectParameter(p As PEParameterSymbol) As XElement Dim result = <Parameter Name=<%= p.Name %>/> Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, p.ParamFlags) result.Add(<ParamFlags><%= paramFlags %></ParamFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.IsParamArray Then Dim peModule = DirectCast(p.ContainingModule, PEModuleSymbol).Module Dim numParamArray = peModule.GetParamArrayCountOrThrow(p.Handle) result.Add(<ParamArray count=<%= numParamArray %>/>) End If Dim type = <Type><%= p.Type %></Type> result.Add(type) If p.IsByRef Then type.@ByRef = "True" End If If p.HasExplicitDefaultValue Then Dim value = p.ExplicitDefaultValue If TypeOf value Is Date Then ' The default display of DateTime is different between Desktop and CoreClr hence ' we need to normalize the value here. value = (CDate(value)).ToString("yyyy-MM-ddTHH:mm:ss") End If result.Add(<Default><%= value %></Default>) End If ' TODO (tomat): add MarshallingInformation Return result End Function Private Function ReflectProperty(p As PEPropertySymbol) As XElement Dim result = <Property Name=<%= p.Name %>/> Dim propertyFlags As New StringBuilder() MetadataSignatureHelper.AppendPropertyAttributes(propertyFlags, p.PropertyFlags) result.Add(<PropertyFlags><%= propertyFlags %></PropertyFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.GetMethod IsNot Nothing Then result.Add(<Get><%= p.GetMethod.ToTestDisplayString() %></Get>) End If If p.SetMethod IsNot Nothing Then result.Add(<Set><%= p.SetMethod.ToTestDisplayString() %></Set>) End If Return result End Function Private Function ReflectEvent(e As PEEventSymbol) As XElement Dim result = <Event Name=<%= e.Name %>/> Dim eventFlags = New StringBuilder() MetadataSignatureHelper.AppendEventAttributes(eventFlags, e.EventFlags) result.Add(<EventFlags><%= eventFlags %></EventFlags>) If e.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(e.GetAttributes())) End If If e.AddMethod IsNot Nothing Then result.Add(<Add><%= e.AddMethod.ToTestDisplayString() %></Add>) End If If e.RemoveMethod IsNot Nothing Then result.Add(<Remove><%= e.RemoveMethod.ToTestDisplayString() %></Remove>) End If If e.RaiseMethod IsNot Nothing Then result.Add(<Raise><%= e.RaiseMethod.ToTestDisplayString() %></Raise>) End If Return result End Function Private Function ReflectField(f As PEFieldSymbol) As XElement Dim result = <Field Name=<%= f.Name %>/> Dim fieldFlags = New StringBuilder() MetadataSignatureHelper.AppendFieldAttributes(fieldFlags, f.FieldFlags) result.Add(<FieldFlags><%= fieldFlags %></FieldFlags>) If f.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(f.GetAttributes())) End If result.Add(<Type><%= f.Type %></Type>) Return result End Function Private Sub AssertReflection(expected As XElement, actual As XElement) Dim expectedStr = expected.ToString().Trim() Dim actualStr = actual.ToString().Trim() Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact> Public Sub SimpleTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class TestAttribute1 Inherits System.Attribute Sub New(x As String) End Sub End Class <System.AttributeUsage(System.AttributeTargets.All And Not System.AttributeTargets.Method)> Public Class TestAttribute2 Inherits System.Attribute Sub New(x As String) End Sub End Class <TestAttribute1("EventDelegate")> Public Delegate Sub EventDelegate(<TestAttribute1("EventDelegate_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.BStr)> z As String) Public MustInherit Class ComClassTestBase MustOverride Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) MustOverride Sub M5(ParamArray z As Integer()) End Class <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Inherits ComClassTestBase Sub M1() End Sub Property P1 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Function M2(x As Integer, ByRef y As Double) As Object Return Nothing End Function Event E1 As EventDelegate <TestAttribute1("TestAttribute1_E2"), TestAttribute2("TestAttribute2_E2")> Event E2(<TestAttribute1("E2_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.AnsiBStr)> z As String) <TestAttribute1("TestAttribute1_M3")> Function M3(<TestAttribute2("TestAttribute2_M3"), [In], Out, MarshalAs(UnmanagedType.AnsiBStr)> Optional ByRef x As String = "M3_x" ) As <TestAttribute1("Return_M3"), MarshalAs(UnmanagedType.BStr)> String Return Nothing End Function Public Overrides Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) End Sub Public NotOverridable Overrides Sub M5(ParamArray z() As Integer) End Sub Public ReadOnly Property P2 As String Get Return Nothing End Get End Property Public WriteOnly Property P3 As String Set(value As String) End Set End Property <TestAttribute1("TestAttribute1_P4")> Public Property P4(<TestAttribute2("TestAttribute2_P4_x"), [In], MarshalAs(UnmanagedType.AnsiBStr)> x As String, Optional y As Decimal = 5.5D ) As <TestAttribute1("Return_M4"), MarshalAs(UnmanagedType.BStr)> String <TestAttribute1("TestAttribute1_P4_Get")> Get Return Nothing End Get <TestAttribute1("TestAttribute1_P4_Set")> Set(<TestAttribute2("TestAttribute2_P4_value"), [In], MarshalAs(UnmanagedType.LPWStr)> value As String) End Set End Property Public Property P5 As Byte Friend Get Return Nothing End Get Set(value As Byte) End Set End Property Public Property P6 As Byte Get Return Nothing End Get Friend Set(value As Byte) End Set End Property Friend Sub M6() End Sub Public Shared Sub M7() End Sub Friend Property P7 As Long Get Return 0 End Get Set(value As Long) End Set End Property Public Shared Property P8 As Long Get Return 0 End Get Set(value As Long) End Set End Property Friend Event E3 As EventDelegate Public Shared Event E4 As EventDelegate Public WithEvents WithEvents1 As ComClassTest Friend Sub Handler(x As Byte, ByRef y As String, z As String) Handles WithEvents1.E1 End Sub Public F1 As Integer End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a><a></a><a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Field Name="F1"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.M2(x As System.Int32, ByRef y As System.Double) As System.Object</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.M3([ByRef x As System.String = "M3_x"]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4([x As System.DateTime = #8/23/1970 12:00:00 AM#], [y As System.Decimal = 4.5])</Implements> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M5(ParamArray z As System.Int32())</Implements> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P5" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Implements> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P6" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M6" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M7" CallingConvention="Default"> <MethodFlags>public static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Return> <Type>ComClassTest</Type> </Return> </Method> <Method Name="set_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed synchronized</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="WithEventsValue"> <ParamFlags></ParamFlags> <Type>ComClassTest</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="Handler" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P5() As System.Byte</Get> <Set>Sub ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P6() As System.Byte</Get> <Set>Sub ComClassTest.set_P6(value As System.Byte)</Set> </Property> <Property Name="P7"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P7() As System.Int64</Get> <Set>Sub ComClassTest.set_P7(value As System.Int64)</Set> </Property> <Property Name="P8"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P8() As System.Int64</Get> <Set>Sub ComClassTest.set_P8(value As System.Int64)</Set> </Property> <Property Name="WithEvents1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_WithEvents1() As ComClassTest</Get> <Set>Sub ComClassTest.set_WithEvents1(WithEventsValue As ComClassTest)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E1(obj As EventDelegate)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_E2</a> </TestAttribute2> </Attributes> <Add>Sub ComClassTest.add_E2(obj As ComClassTest.E2EventHandler)</Add> <Remove>Sub ComClassTest.remove_E2(obj As ComClassTest.E2EventHandler)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E3(obj As EventDelegate)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E4(obj As EventDelegate)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>4</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>5</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>6</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Byte</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Event E1 As System.Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217")> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) AssertTheseDiagnostics(verifier.Compilation, <expected> BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'ComClassTest' but 'ComClassTest' has no public members that can be exposed to COM; therefore, no COM interfaces are generated. Public Class ComClassTest ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SimpleTest6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217", "EA329A13-16A0-478d-B41F-47583A761FF2", InterfaceShadows:=True)> Public Class ComClassTest Sub M1() Dim x as Integer = 12 Dim y = Function() x End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> <a>EA329A13-16A0-478d-B41F-47583A761FF2</a> <Named Name="InterfaceShadows">True</Named> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Class Name="_Closure$__1-0"> <TypeDefFlags>nested assembly auto ansi sealed</TypeDefFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Field Name="$VB$Local_x"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="_Lambda$__0" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> </Class> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub Test_ERR_ComClassOnGeneric() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest(Of T) End Class Public Class ComClassTest1(Of T) <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest2 End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest(Of T) ~~~~~~~~~~~~ BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub Test_ERR_BadAttributeUuid2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("1", "2", "3")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '1' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '2' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '3' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassDuplicateGuids1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "")> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest5 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "0")> Public Class ComClassTest6 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "0", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest7 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'ComClassTest1' cannot have the same value. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest6 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_Guid() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), Guid("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'GuidAttribute' cannot both be applied to the same class. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ClassInterface() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ClassInterface(0)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ClassInterface(ClassInterfaceType.None)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComSourceInterfaces() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces("x")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1))> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest5 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest3 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest5 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComVisible() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComVisible(False)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible(True)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible()> Public Class ComClassTest3 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected><![CDATA[ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComVisibleAttribute(False)' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC30455: Argument not specified for parameter 'visibility' of 'Public Overloads Sub New(visibility As Boolean)'. <Microsoft.VisualBasic.ComClass(), ComVisible()> ~~~~~~~~~~ ]]></expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassRequiresPublicClass1_ERR_ComClassRequiresPublicClass2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Friend Class ComClassTest1 Public Sub Goo() End Sub End Class Friend Class ComClassTest2 Friend Class ComClassTest3 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest4 Public Sub Goo() End Sub End Class End Class End Class Friend Class ComClassTest5 Public Class ComClassTest6 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest7 Public Sub Goo() End Sub End Class End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest1' because it is not declared 'Public'. Friend Class ComClassTest1 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest4' because its container 'ComClassTest3' is not declared 'Public'. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest7' because its container 'ComClassTest5' is not declared 'Public'. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassCantBeAbstract0() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public MustInherit Class ComClassTest1 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'. Public MustInherit Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_MemberConflictWithSynth4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest1 As ComClassTest1 Private Sub __ComClassTest1() End Sub Protected Sub __ComClassTest1(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest2 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest2 As ComClassTest2 Private Sub __ComClassTest2() End Sub Protected Sub __ComClassTest2(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest3 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest3 As ComClassTest3 Private Sub __ComClassTest3() End Sub Protected Sub __ComClassTest3(x As Integer) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31058: Conflicts with 'Interface _ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. WithEvents ComClassTest1 As ComClassTest1 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Private Sub __ComClassTest1() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Protected Sub __ComClassTest1(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. WithEvents ComClassTest2 As ComClassTest2 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Private Sub __ComClassTest2() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Protected Sub __ComClassTest2(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. WithEvents ComClassTest3 As ComClassTest3 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Private Sub __ComClassTest3() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Protected Sub __ComClassTest3(x As Integer) ~~~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassPropertySetObject1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Property P1 As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property Public ReadOnly Property P3 As Object Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42102: 'Public Property P1 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public Property P1 As Object ~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassGenericMethod() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo(Of T)() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30943: Generic methods cannot be exposed to COM. Public Sub Goo(Of T)() ~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComClassWithWarnings() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Public Sub _ComClassTest1() End Sub Public Sub __ComClassTest1() End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub M1() End Sub Public Event E1() Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest1+__ComClassTest1</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest1._ComClassTest1</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest1.set_P2(value As System.Object)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest1.add_E1(obj As ComClassTest1.E1EventHandler)</Add> <Remove>Sub ComClassTest1.remove_E1(obj As ComClassTest1.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Set> </Property> </Interface> <Interface Name="__ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest1")) End Sub) Dim warnings = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDiagnostics(verifier.Compilation, warnings) End Sub <Fact> Public Sub Test_ERR_InvalidAttributeUsage2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Module ComClassTest1 Public Sub M1() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30662: Attribute 'ComClassAttribute' cannot be applied to 'ComClassTest1' because the attribute is not valid on this declaration type. Public Module ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComInvisibleMembers() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <ComVisible(False)> Public Sub M1(Of T)() End Sub Public Sub M2() End Sub <ComVisible(False)> Public Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2 As Integer <ComVisible(False)> Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P3 As Integer Get Return 0 End Get <ComVisible(False)> Set(value As Integer) End Set End Property Public ReadOnly Property P4 As Integer <ComVisible(False)> Get Return 0 End Get End Property Public WriteOnly Property P5 As Integer <ComVisible(False)> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="Generic, HasThis"> <MethodFlags>public instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P3() As System.Int32</Get> <Set>Sub ComClassTest.set_P3(value As System.Int32)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P4() As System.Int32</Get> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P5(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("{7666AC25-855F-4534-BC55-27BF09D49D44}", "(7666AC25-855F-4534-BC55-27BF09D49D45)", "7666AC25855F4534BC5527BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '(7666AC25-855F-4534-BC55-27BF09D49D45)' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '7666AC25855F4534BC5527BF09D49D46' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '{7666AC25-855F-4534-BC55-27BF09D49D44}' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComSourceInterfacesAttribute1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Namespace nS Class Test2 End Class End Namespace Namespace NS Public Class ComClassTest1 Class ComClassTest2 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest3 Public Event E1() End Class End Class End Class End Namespace Namespace ns Class Test1 End Class End Namespace ]]></file> </compilation> Dim expected = <Class Name="ComClassTest3"> <TypeDefFlags>nested public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>NS.ComClassTest1+ComClassTest2+ComClassTest3+__ComClassTest3</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>NS.ComClassTest1.ComClassTest2.ComClassTest3._ComClassTest3</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.add_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Add> <Remove>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.remove_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "NS.ComClassTest1+ComClassTest2+ComClassTest3")) End Sub) End Sub <Fact()> Public Sub OrderOfAccessors() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Property P1 As Integer Set(value As Integer) End Set Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Sub M2() End Sub Sub M3() End Sub Event E1 As Action <DispId(16)> Event E2 As Action Event E3 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(1)> Sub M2() End Sub <DispId(3)> Friend Sub M3() End Sub Sub M4() End Sub Event E1 As Action <DispId(2)> Event E2 As Action <DispId(3)> Friend Event E3 As Action Event E4 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E4(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId7() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId8() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId9() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId10() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId11() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default ReadOnly Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId12() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default WriteOnly Property P1(x As Integer) As Integer <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId13() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId14() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(13)> Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId15() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Return Nothing End Function Sub GetEnumerator() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.GetEnumerator()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId16() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator() As Integer Return Nothing End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId17() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest ReadOnly Property GetEnumerator() As Collections.IEnumerator Get Return Nothing End Get End Property ReadOnly Property GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DefaultProperty1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Reflection.DefaultMember("p1")> Public Class ComClassTest Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property Event E1 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>p1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub DispId18() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property <DispId(-1)> Sub M1() End Sub <DispId(-2)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'P1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. ReadOnly Property P1(x As Integer) As Integer ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Sub M1() ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DispId19() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Sub M1() End Sub <DispId(0)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Sub M1() ~~ BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DefaultProperty2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub Serializable_and_SpecialName() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Serializable()> <System.Runtime.CompilerServices.SpecialName()> Public Class ComClassTest <System.Runtime.CompilerServices.SpecialName()> Sub M1() End Sub <System.Runtime.CompilerServices.SpecialName()> Event E1 As Action <System.Runtime.CompilerServices.SpecialName()> Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property P2 As Integer <System.Runtime.CompilerServices.SpecialName()> Get Return 0 End Get <System.Runtime.CompilerServices.SpecialName()> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi serializable specialname</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Event Name="E1"> <EventFlags>specialname</EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact(), WorkItem(531506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531506")> Public Sub Bug18218() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Assembly: GuidAttribute("5F025F24-FAEA-4C2F-9EF6-C89A8FC90101")> <Assembly: ComVisible(True)> <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Implements I6 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F" Public Const InterfaceId As String = "5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512" Public Const EventsId As String = "33241EB2-DFC5-4164-998E-A6577B0DA960" #End Region Public Interface I6 End Interface Public Property Scen1 As String Get Return Nothing End Get Set(ByVal Value As String) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> <a>33241EB2-DFC5-4164-998E-A6577B0DA960</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Implements>ComClass1.I6</Implements> <Field Name="ClassId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="InterfaceId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="EventsId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.get_Scen1() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Implements> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Get>Function ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1.set_Scen1(Value As System.String)</Set> </Property> <Interface Name="I6"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> </Interface> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClass1._ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1")) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664574")> Public Sub Bug664574() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Function dfoo(<MarshalAs(UnmanagedType.Currency)> ByVal x As Decimal) As <MarshalAs(UnmanagedType.Currency)> Decimal Return x + 1.1D End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> <a>8F12C15B-4CA9-450C-9C85-37E9B74164B8</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.dfoo(x As System.Decimal) As System.Decimal</Implements> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1", Function(s) Return s.Kind = SymbolKind.NamedType OrElse s.Name = "dfoo" End Function)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664583")> Public Sub Bug664583() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Readonly Property Goo As Integer Get Return 0 End Get End Property Structure Struct1 Public member1 As Integer Structure Struct2 Public member12 As Integer End Structure End Structure Structure struct2 Public member2 As Integer End Structure End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim ComClass1_Struct1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1"), PENamedTypeSymbol) Dim ComClass1_Struct1_Struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1+Struct2"), PENamedTypeSymbol) Dim ComClass1_struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+struct2"), PENamedTypeSymbol) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_struct2.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(700050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700050")> Public Sub Bug700050() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() End Sub End Module <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Public Const ClassId As String = "" Public Const InterfaceId As String = "" Public Const EventsId As String = "" Public Sub New() End Sub Public Sub Goo() End Sub Public Property oBrowser As Object ' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim _ComClass1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+_ComClass1"), PENamedTypeSymbol) Assert.Equal(0, _ComClass1.GetMembers("oBrowser").Length) End Sub).VerifyDiagnostics() 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.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class ComClassTests Inherits BasicTestBase Private Function ReflectComClass( pm As PEModuleSymbol, comClassName As String, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing ) As XElement Dim type As PENamedTypeSymbol = DirectCast(pm.ContainingAssembly.GetTypeByMetadataName(comClassName), PENamedTypeSymbol) Dim combinedFilter = Function(m As Symbol) Return (memberFilter Is Nothing OrElse memberFilter(m)) AndAlso (m.ContainingSymbol IsNot type OrElse m.Kind <> SymbolKind.NamedType OrElse Not DirectCast(m, NamedTypeSymbol).IsDelegateType()) End Function Return ReflectType(type, combinedFilter) End Function Private Function ReflectType(type As PENamedTypeSymbol, Optional memberFilter As Func(Of Symbol, Boolean) = Nothing) As XElement Dim result = <<%= type.TypeKind.ToString() %> Name=<%= type.Name %>></> Dim typeDefFlags = New StringBuilder() MetadataSignatureHelper.AppendTypeAttributes(typeDefFlags, type.TypeDefFlags) result.Add(<TypeDefFlags><%= typeDefFlags %></TypeDefFlags>) If type.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(type.GetAttributes())) End If For Each [interface] In type.Interfaces result.Add(<Implements><%= [interface].ToTestDisplayString() %></Implements>) Next For Each member In type.GetMembers If memberFilter IsNot Nothing AndAlso Not memberFilter(member) Then Continue For End If Select Case member.Kind Case SymbolKind.NamedType result.Add(ReflectType(DirectCast(member, PENamedTypeSymbol), memberFilter)) Case SymbolKind.Method result.Add(ReflectMethod(DirectCast(member, PEMethodSymbol))) Case SymbolKind.Property result.Add(ReflectProperty(DirectCast(member, PEPropertySymbol))) Case SymbolKind.Event result.Add(ReflectEvent(DirectCast(member, PEEventSymbol))) Case SymbolKind.Field result.Add(ReflectField(DirectCast(member, PEFieldSymbol))) Case Else Throw TestExceptionUtilities.UnexpectedValue(member.Kind) End Select Next Return result End Function Private Function ReflectAttributes(attrData As ImmutableArray(Of VisualBasicAttributeData)) As XElement Dim result = <Attributes></Attributes> For Each attr In attrData Dim application = <<%= attr.AttributeClass.ToTestDisplayString() %>/> result.Add(application) application.Add(<ctor><%= attr.AttributeConstructor.ToTestDisplayString() %></ctor>) For Each arg In attr.CommonConstructorArguments application.Add(<a><%= arg.Value.ToString() %></a>) Next For Each named In attr.CommonNamedArguments application.Add(<Named Name=<%= named.Key %>><%= named.Value.Value.ToString() %></Named>) Next Next Return result End Function Private Function ReflectMethod(m As PEMethodSymbol) As XElement Dim result = <Method Name=<%= m.Name %> CallingConvention=<%= m.CallingConvention %>/> Dim methodFlags = New StringBuilder() Dim methodImplFlags = New StringBuilder() MetadataSignatureHelper.AppendMethodAttributes(methodFlags, m.MethodFlags) MetadataSignatureHelper.AppendMethodImplAttributes(methodImplFlags, m.MethodImplFlags) result.Add(<MethodFlags><%= methodFlags %></MethodFlags>) result.Add(<MethodImplFlags><%= methodImplFlags %></MethodImplFlags>) If m.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(m.GetAttributes())) End If For Each impl In m.ExplicitInterfaceImplementations result.Add(<Implements><%= impl.ToTestDisplayString() %></Implements>) Next For Each param In m.Parameters result.Add(ReflectParameter(DirectCast(param, PEParameterSymbol))) Next Dim ret = <Return><Type><%= m.ReturnType %></Type></Return> result.Add(ret) Dim retFlags = m.ReturnParam.ParamFlags If retFlags <> 0 Then Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, retFlags) ret.Add(<ParamFlags><%= paramFlags %></ParamFlags>) End If If m.GetReturnTypeAttributes().Length > 0 Then ret.Add(ReflectAttributes(m.GetReturnTypeAttributes())) End If Return result End Function Private Function ReflectParameter(p As PEParameterSymbol) As XElement Dim result = <Parameter Name=<%= p.Name %>/> Dim paramFlags = New StringBuilder() MetadataSignatureHelper.AppendParameterAttributes(paramFlags, p.ParamFlags) result.Add(<ParamFlags><%= paramFlags %></ParamFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.IsParamArray Then Dim peModule = DirectCast(p.ContainingModule, PEModuleSymbol).Module Dim numParamArray = peModule.GetParamArrayCountOrThrow(p.Handle) result.Add(<ParamArray count=<%= numParamArray %>/>) End If Dim type = <Type><%= p.Type %></Type> result.Add(type) If p.IsByRef Then type.@ByRef = "True" End If If p.HasExplicitDefaultValue Then Dim value = p.ExplicitDefaultValue If TypeOf value Is Date Then ' The default display of DateTime is different between Desktop and CoreClr hence ' we need to normalize the value here. value = (CDate(value)).ToString("yyyy-MM-ddTHH:mm:ss") End If result.Add(<Default><%= value %></Default>) End If ' TODO (tomat): add MarshallingInformation Return result End Function Private Function ReflectProperty(p As PEPropertySymbol) As XElement Dim result = <Property Name=<%= p.Name %>/> Dim propertyFlags As New StringBuilder() MetadataSignatureHelper.AppendPropertyAttributes(propertyFlags, p.PropertyFlags) result.Add(<PropertyFlags><%= propertyFlags %></PropertyFlags>) If p.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(p.GetAttributes())) End If If p.GetMethod IsNot Nothing Then result.Add(<Get><%= p.GetMethod.ToTestDisplayString() %></Get>) End If If p.SetMethod IsNot Nothing Then result.Add(<Set><%= p.SetMethod.ToTestDisplayString() %></Set>) End If Return result End Function Private Function ReflectEvent(e As PEEventSymbol) As XElement Dim result = <Event Name=<%= e.Name %>/> Dim eventFlags = New StringBuilder() MetadataSignatureHelper.AppendEventAttributes(eventFlags, e.EventFlags) result.Add(<EventFlags><%= eventFlags %></EventFlags>) If e.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(e.GetAttributes())) End If If e.AddMethod IsNot Nothing Then result.Add(<Add><%= e.AddMethod.ToTestDisplayString() %></Add>) End If If e.RemoveMethod IsNot Nothing Then result.Add(<Remove><%= e.RemoveMethod.ToTestDisplayString() %></Remove>) End If If e.RaiseMethod IsNot Nothing Then result.Add(<Raise><%= e.RaiseMethod.ToTestDisplayString() %></Raise>) End If Return result End Function Private Function ReflectField(f As PEFieldSymbol) As XElement Dim result = <Field Name=<%= f.Name %>/> Dim fieldFlags = New StringBuilder() MetadataSignatureHelper.AppendFieldAttributes(fieldFlags, f.FieldFlags) result.Add(<FieldFlags><%= fieldFlags %></FieldFlags>) If f.GetAttributes().Length > 0 Then result.Add(ReflectAttributes(f.GetAttributes())) End If result.Add(<Type><%= f.Type %></Type>) Return result End Function Private Sub AssertReflection(expected As XElement, actual As XElement) Dim expectedStr = expected.ToString().Trim() Dim actualStr = actual.ToString().Trim() Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact> Public Sub SimpleTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices Public Class TestAttribute1 Inherits System.Attribute Sub New(x As String) End Sub End Class <System.AttributeUsage(System.AttributeTargets.All And Not System.AttributeTargets.Method)> Public Class TestAttribute2 Inherits System.Attribute Sub New(x As String) End Sub End Class <TestAttribute1("EventDelegate")> Public Delegate Sub EventDelegate(<TestAttribute1("EventDelegate_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.BStr)> z As String) Public MustInherit Class ComClassTestBase MustOverride Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) MustOverride Sub M5(ParamArray z As Integer()) End Class <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Inherits ComClassTestBase Sub M1() End Sub Property P1 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Function M2(x As Integer, ByRef y As Double) As Object Return Nothing End Function Event E1 As EventDelegate <TestAttribute1("TestAttribute1_E2"), TestAttribute2("TestAttribute2_E2")> Event E2(<TestAttribute1("E2_x")> x As Byte, ByRef y As String, <MarshalAs(UnmanagedType.AnsiBStr)> z As String) <TestAttribute1("TestAttribute1_M3")> Function M3(<TestAttribute2("TestAttribute2_M3"), [In], Out, MarshalAs(UnmanagedType.AnsiBStr)> Optional ByRef x As String = "M3_x" ) As <TestAttribute1("Return_M3"), MarshalAs(UnmanagedType.BStr)> String Return Nothing End Function Public Overrides Sub M4(Optional x As Date = #8/23/1970#, Optional y As Decimal = 4.5D) End Sub Public NotOverridable Overrides Sub M5(ParamArray z() As Integer) End Sub Public ReadOnly Property P2 As String Get Return Nothing End Get End Property Public WriteOnly Property P3 As String Set(value As String) End Set End Property <TestAttribute1("TestAttribute1_P4")> Public Property P4(<TestAttribute2("TestAttribute2_P4_x"), [In], MarshalAs(UnmanagedType.AnsiBStr)> x As String, Optional y As Decimal = 5.5D ) As <TestAttribute1("Return_M4"), MarshalAs(UnmanagedType.BStr)> String <TestAttribute1("TestAttribute1_P4_Get")> Get Return Nothing End Get <TestAttribute1("TestAttribute1_P4_Set")> Set(<TestAttribute2("TestAttribute2_P4_value"), [In], MarshalAs(UnmanagedType.LPWStr)> value As String) End Set End Property Public Property P5 As Byte Friend Get Return Nothing End Get Set(value As Byte) End Set End Property Public Property P6 As Byte Get Return Nothing End Get Friend Set(value As Byte) End Set End Property Friend Sub M6() End Sub Public Shared Sub M7() End Sub Friend Property P7 As Long Get Return 0 End Get Set(value As Long) End Set End Property Public Shared Property P8 As Long Get Return 0 End Get Set(value As Long) End Set End Property Friend Event E3 As EventDelegate Public Shared Event E4 As EventDelegate Public WithEvents WithEvents1 As ComClassTest Friend Sub Handler(x As Byte, ByRef y As String, z As String) Handles WithEvents1.E1 End Sub Public F1 As Integer End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a><a></a><a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Field Name="F1"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.M2(x As System.Int32, ByRef y As System.Double) As System.Object</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E2EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.M3([ByRef x As System.String = "M3_x"]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4([x As System.DateTime = #8/23/1970 12:00:00 AM#], [y As System.Decimal = 4.5])</Implements> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public hidebysig strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M5(ParamArray z As System.Int32())</Implements> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Implements> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P5" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Implements> <Return> <Type>Byte</Type> </Return> </Method> <Method Name="set_P6" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M6" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M7" CallingConvention="Default"> <MethodFlags>public static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P7" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Long</Type> </Return> </Method> <Method Name="set_P8" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Long</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="Default"> <MethodFlags>public specialname static</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>EventDelegate</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Return> <Type>ComClassTest</Type> </Return> </Method> <Method Name="set_WithEvents1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual instance</MethodFlags> <MethodImplFlags>cil managed synchronized</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="WithEventsValue"> <ParamFlags></ParamFlags> <Type>ComClassTest</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="Handler" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P5() As System.Byte</Get> <Set>Sub ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P6() As System.Byte</Get> <Set>Sub ComClassTest.set_P6(value As System.Byte)</Set> </Property> <Property Name="P7"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P7() As System.Int64</Get> <Set>Sub ComClassTest.set_P7(value As System.Int64)</Set> </Property> <Property Name="P8"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P8() As System.Int64</Get> <Set>Sub ComClassTest.set_P8(value As System.Int64)</Set> </Property> <Property Name="WithEvents1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_WithEvents1() As ComClassTest</Get> <Set>Sub ComClassTest.set_WithEvents1(WithEventsValue As ComClassTest)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E1(obj As EventDelegate)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_E2</a> </TestAttribute2> </Attributes> <Add>Sub ComClassTest.add_E2(obj As ComClassTest.E2EventHandler)</Add> <Remove>Sub ComClassTest.remove_E2(obj As ComClassTest.E2EventHandler)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E3(obj As EventDelegate)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As EventDelegate)</Add> <Remove>Sub ComClassTest.remove_E4(obj As EventDelegate)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">Double</Type> </Parameter> <Return> <Type>Object</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>4</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_M3</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] [in] [out] marshal default</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_M3</a> </TestAttribute2> </Attributes> <Type ByRef="True">String</Type> <Default>M3_x</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M3</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>5</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt]</ParamFlags> <Type>Date</Type> <Default>1970-08-23T00:00:00</Default> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>4.5</Default> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M5" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>6</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="z"> <ParamFlags></ParamFlags> <ParamArray count="1"/> <Type>Integer()</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Get</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Return> <Type>String</Type> <ParamFlags>marshal</ParamFlags> <Attributes> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>Return_M4</a> </TestAttribute1> </Attributes> </Return> </Method> <Method Name="set_P4" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4_Set</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_x</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Parameter Name="y"> <ParamFlags>[opt]</ParamFlags> <Type>Decimal</Type> <Default>5.5</Default> </Parameter> <Parameter Name="value"> <ParamFlags>[in] marshal</ParamFlags> <Attributes> <TestAttribute2> <ctor>Sub TestAttribute2..ctor(x As System.String)</ctor> <a>TestAttribute2_P4_value</a> </TestAttribute2> </Attributes> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P6" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Byte</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>7</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.String</Get> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>8</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P3(value As System.String)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>9</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_P4</a> </TestAttribute1> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P4(x As System.String, [y As System.Decimal = 5.5]) As System.String</Get> <Set>Sub ComClassTest._ComClassTest.set_P4(x As System.String, [y As System.Decimal = 5.5], value As System.String)</Set> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>10</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P5(value As System.Byte)</Set> </Property> <Property Name="P6"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>11</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P6() As System.Byte</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> <TestAttribute1> <ctor>Sub TestAttribute1..ctor(x As System.String)</ctor> <a>TestAttribute1_E2</a> </TestAttribute1> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Byte</Type> </Parameter> <Parameter Name="y"> <ParamFlags></ParamFlags> <Type ByRef="True">String</Type> </Parameter> <Parameter Name="z"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Event E1 As System.Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217")> Public Class ComClassTest Sub M1() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub SimpleTest5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) AssertTheseDiagnostics(verifier.Compilation, <expected> BC40011: 'Microsoft.VisualBasic.ComClassAttribute' is specified for class 'ComClassTest' but 'ComClassTest' has no public members that can be exposed to COM; therefore, no COM interfaces are generated. Public Class ComClassTest ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub SimpleTest6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "54388137-8A76-491e-AA3A-853E23AC1217", "EA329A13-16A0-478d-B41F-47583A761FF2", InterfaceShadows:=True)> Public Class ComClassTest Sub M1() Dim x as Integer = 12 Dim y = Function() x End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> <a>EA329A13-16A0-478d-B41F-47583A761FF2</a> <Named Name="InterfaceShadows">True</Named> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>54388137-8A76-491e-AA3A-853E23AC1217</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Class Name="_Closure$__1-0"> <TypeDefFlags>nested assembly auto ansi sealed</TypeDefFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Field Name="$VB$Local_x"> <FieldFlags>public instance</FieldFlags> <Type>Integer</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="_Lambda$__0" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> </Class> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact> Public Sub Test_ERR_ComClassOnGeneric() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest(Of T) End Class Public Class ComClassTest1(Of T) <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest2 End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest(Of T) ~~~~~~~~~~~~ BC31527: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is generic or contained inside a generic type. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub Test_ERR_BadAttributeUuid2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("1", "2", "3")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '1' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '2' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '3' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassDuplicateGuids1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("7666AC25-855F-4534-BC55-27BF09D49D46", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "")> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest5 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "00000000-0000-0000-0000-000000000000", "0")> Public Class ComClassTest6 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass("", "0", "00000000-0000-0000-0000-000000000000")> Public Class ComClassTest7 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32507: 'InterfaceId' and 'EventsId' parameters for 'Microsoft.VisualBasic.ComClassAttribute' on 'ComClassTest1' cannot have the same value. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest6 ~~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '0' is not correct. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_Guid() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), Guid("7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'GuidAttribute' cannot both be applied to the same class. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ClassInterface() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ClassInterface(0)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ClassInterface(ClassInterfaceType.None)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ClassInterfaceAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComSourceInterfaces() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces("x")> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1))> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest3 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest4 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComSourceInterfaces(GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1), GetType(ComClassTest1))> Public Class ComClassTest5 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest2 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest3 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComSourceInterfacesAttribute' cannot both be applied to the same class. Public Class ComClassTest5 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassAndReservedAttribute1_ComVisible() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(), ComVisible(False)> Public Class ComClassTest1 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible(True)> Public Class ComClassTest2 Public Sub Goo() End Sub End Class <Microsoft.VisualBasic.ComClass(), ComVisible()> Public Class ComClassTest3 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected><![CDATA[ BC32501: 'Microsoft.VisualBasic.ComClassAttribute' and 'ComVisibleAttribute(False)' cannot both be applied to the same class. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC30455: Argument not specified for parameter 'visibility' of 'Public Overloads Sub New(visibility As Boolean)'. <Microsoft.VisualBasic.ComClass(), ComVisible()> ~~~~~~~~~~ ]]></expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassRequiresPublicClass1_ERR_ComClassRequiresPublicClass2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Friend Class ComClassTest1 Public Sub Goo() End Sub End Class Friend Class ComClassTest2 Friend Class ComClassTest3 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest4 Public Sub Goo() End Sub End Class End Class End Class Friend Class ComClassTest5 Public Class ComClassTest6 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest7 Public Sub Goo() End Sub End Class End Class End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32509: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest1' because it is not declared 'Public'. Friend Class ComClassTest1 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest4' because its container 'ComClassTest3' is not declared 'Public'. Public Class ComClassTest4 ~~~~~~~~~~~~~ BC32504: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to 'ComClassTest7' because its container 'ComClassTest5' is not declared 'Public'. Public Class ComClassTest7 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassCantBeAbstract0() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public MustInherit Class ComClassTest1 Public Sub Goo() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32508: 'Microsoft.VisualBasic.ComClassAttribute' cannot be applied to a class that is declared 'MustInherit'. Public MustInherit Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_MemberConflictWithSynth4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest1 As ComClassTest1 Private Sub __ComClassTest1() End Sub Protected Sub __ComClassTest1(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest2 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest2 As ComClassTest2 Private Sub __ComClassTest2() End Sub Protected Sub __ComClassTest2(x As Integer) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest3 Public Sub Goo() End Sub Public Event E1() WithEvents ComClassTest3 As ComClassTest3 Private Sub __ComClassTest3() End Sub Protected Sub __ComClassTest3(x As Integer) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC31058: Conflicts with 'Interface _ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. WithEvents ComClassTest1 As ComClassTest1 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Private Sub __ComClassTest1() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest1', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest1'. Protected Sub __ComClassTest1(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. WithEvents ComClassTest2 As ComClassTest2 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Private Sub __ComClassTest2() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest2', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest2'. Protected Sub __ComClassTest2(x As Integer) ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface _ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. WithEvents ComClassTest3 As ComClassTest3 ~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Private Sub __ComClassTest3() ~~~~~~~~~~~~~~~ BC31058: Conflicts with 'Interface __ComClassTest3', which is implicitly declared for 'ComClassAttribute' in Class 'ComClassTest3'. Protected Sub __ComClassTest3(x As Integer) ~~~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=False)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassInterfaceShadows5_3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Private Sub _ComClassTest1() End Sub Private Sub __ComClassTest1() End Sub Protected Sub _ComClassTest1(x As Integer) End Sub Protected Sub __ComClassTest1(x As Integer) End Sub Friend Sub _ComClassTest1(x As Integer, y As Integer) End Sub Friend Sub __ComClassTest1(x As Integer, y As Integer) End Sub Protected Friend Sub _ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Protected Friend Sub __ComClassTest1(x As Integer, y As Integer, z As Integer) End Sub Public Sub _ComClassTest1(x As Long) End Sub Public Sub __ComClassTest1(x As Long) End Sub End Class <Microsoft.VisualBasic.ComClass(InterfaceShadows:=True)> Public Class ComClassTest1 Inherits ComClassBase Public Sub Goo() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_WRN_ComClassPropertySetObject1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Property P1 As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property Public ReadOnly Property P3 As Object Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC42102: 'Public Property P1 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public Property P1 As Object ~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact> Public Sub Test_ERR_ComClassGenericMethod() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Public Sub Goo(Of T)() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30943: Generic methods cannot be exposed to COM. Public Sub Goo(Of T)() ~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComClassWithWarnings() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class ComClassBase Public Sub _ComClassTest1() End Sub Public Sub __ComClassTest1() End Sub End Class <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest1 Inherits ComClassBase Public Sub M1() End Sub Public Event E1() Public WriteOnly Property P2 As Object Set(value As Object) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest1+__ComClassTest1</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest1._ComClassTest1</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest1.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest1.set_P2(value As System.Object)</Set> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest1.add_E1(obj As ComClassTest1.E1EventHandler)</Add> <Remove>Sub ComClassTest1.remove_E1(obj As ComClassTest1.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Object</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest1._ComClassTest1.set_P2(value As System.Object)</Set> </Property> </Interface> <Interface Name="__ComClassTest1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest1")) End Sub) Dim warnings = <expected> BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '_ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42101: 'Microsoft.VisualBasic.ComClassAttribute' on class 'ComClassTest1' implicitly declares Interface '__ComClassTest1', which conflicts with a member of the same name in Class 'ComClassBase'. Use 'Microsoft.VisualBasic.ComClassAttribute(InterfaceShadows:=True)' if you want to hide the name on the base ComClassBase. Public Class ComClassTest1 ~~~~~~~~~~~~~ BC42102: 'Public WriteOnly Property P2 As Object' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. Public WriteOnly Property P2 As Object ~~ </expected> AssertTheseDiagnostics(verifier.Compilation, warnings) End Sub <Fact> Public Sub Test_ERR_InvalidAttributeUsage2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Module ComClassTest1 Public Sub M1() End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC30662: Attribute 'ComClassAttribute' cannot be applied to 'ComClassTest1' because the attribute is not valid on this declaration type. Public Module ComClassTest1 ~~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComInvisibleMembers() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <ComVisible(False)> Public Sub M1(Of T)() End Sub Public Sub M2() End Sub <ComVisible(False)> Public Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P2 As Integer <ComVisible(False)> Get Return 0 End Get Set(value As Integer) End Set End Property Public Property P3 As Integer Get Return 0 End Get <ComVisible(False)> Set(value As Integer) End Set End Property Public ReadOnly Property P4 As Integer <ComVisible(False)> Get Return 0 End Get End Property Public WriteOnly Property P5 As Integer <ComVisible(False)> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="Generic, HasThis"> <MethodFlags>public instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P5" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>False</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P3() As System.Int32</Get> <Set>Sub ComClassTest.set_P3(value As System.Int32)</Set> </Property> <Property Name="P4"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P4() As System.Int32</Get> </Property> <Property Name="P5"> <PropertyFlags></PropertyFlags> <Set>Sub ComClassTest.set_P5(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P3" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Property Name="P3"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P3() As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "7666AC25-855F-4534-BC55-27BF09D49D46", "")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass("", "", "7666AC25-855F-4534-BC55-27BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>ComClassTest.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As ComClassTest.E1EventHandler)</Add> <Remove>Sub ComClassTest.remove_E1(obj As ComClassTest.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>7666AC25-855F-4534-BC55-27BF09D49D46</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub GuidAttributeTest3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("{7666AC25-855F-4534-BC55-27BF09D49D44}", "(7666AC25-855F-4534-BC55-27BF09D49D45)", "7666AC25855F4534BC5527BF09D49D46")> Public Class ComClassTest Public Sub M1() End Sub Public Event E1() End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) Dim expected = <expected> BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '(7666AC25-855F-4534-BC55-27BF09D49D45)' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '7666AC25855F4534BC5527BF09D49D46' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ BC32500: 'ComClassAttribute' cannot be applied because the format of the GUID '{7666AC25-855F-4534-BC55-27BF09D49D44}' is not correct. Public Class ComClassTest ~~~~~~~~~~~~ </expected> AssertTheseDeclarationDiagnostics(compilation, expected) AssertTheseDiagnostics(compilation, expected) End Sub <Fact()> Public Sub ComSourceInterfacesAttribute1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Namespace nS Class Test2 End Class End Namespace Namespace NS Public Class ComClassTest1 Class ComClassTest2 <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest3 Public Event E1() End Class End Class End Class End Namespace Namespace ns Class Test1 End Class End Namespace ]]></file> </compilation> Dim expected = <Class Name="ComClassTest3"> <TypeDefFlags>nested public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>NS.ComClassTest1+ComClassTest2+ComClassTest3+__ComClassTest3</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>NS.ComClassTest1.ComClassTest2.ComClassTest3._ComClassTest3</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.add_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Add> <Remove>Sub NS.ComClassTest1.ComClassTest2.ComClassTest3.remove_E1(obj As NS.ComClassTest1.ComClassTest2.ComClassTest3.E1EventHandler)</Remove> </Event> <Interface Name="_ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> </Interface> <Interface Name="__ComClassTest3"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "NS.ComClassTest1+ComClassTest2+ComClassTest3")) End Sub) End Sub <Fact()> Public Sub OrderOfAccessors() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass("", "", "")> Public Class ComClassTest Property P1 As Integer Set(value As Integer) End Set Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a></a> <a></a> <a></a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Sub M2() End Sub Sub M3() End Sub Event E1 As Action <DispId(16)> Event E2 As Action Event E3 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(1)> Sub M2() End Sub <DispId(3)> Friend Sub M3() End Sub Sub M4() End Sub Event E1 As Action <DispId(2)> Event E2 As Action <DispId(3)> Friend Event E3 As Action Event E4 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.M2()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>assembly instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M4()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E2" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E3" CallingConvention="HasThis"> <MethodFlags>assembly specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E4" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Event Name="E2"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E2(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E2(obj As System.Action)</Remove> </Event> <Event Name="E3"> <EventFlags></EventFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Add>Sub ComClassTest.add_E3(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E3(obj As System.Action)</Remove> </Event> <Event Name="E4"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E4(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E4(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E2" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="E4" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId3() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId4() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Property P1 As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId5() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId6() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Property P1 As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId7() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer <DispId(16)> Get Return 0 End Get Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId8() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(15)> Default Property P1(x As Integer) As Integer Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId9() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId10() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId11() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default ReadOnly Property P1(x As Integer) As Integer <DispId(15)> Get Return 0 End Get End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>15</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId12() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(17)> Default WriteOnly Property P1(x As Integer) As Integer <DispId(16)> Set(value As Integer) End Set End Property Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>16</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>17</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Set>Sub ComClassTest._ComClassTest.set_P1(x As System.Int32, value As System.Int32)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId13() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId14() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Sub M1() End Sub <DispId(13)> Function GetEnumerator() As Collections.IEnumerator Return Nothing End Function Sub M3() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M3()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>13</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="M3" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId15() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Return Nothing End Function Sub GetEnumerator() End Sub End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.GetEnumerator()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId16() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest Function GetEnumerator() As Integer Return Nothing End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.GetEnumerator() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DispId17() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest ReadOnly Property GetEnumerator() As Collections.IEnumerator Get Return Nothing End Get End Property ReadOnly Property GetEnumerator(Optional x As Integer = 0) As Collections.IEnumerator Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Implements> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Implements> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Method Name="get_GetEnumerator" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>[opt] default</ParamFlags> <Type>Integer</Type> <Default>0</Default> </Parameter> <Return> <Type>System.Collections.IEnumerator</Type> </Return> </Method> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>-4</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator() As System.Collections.IEnumerator</Get> </Property> <Property Name="GetEnumerator"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_GetEnumerator([x As System.Int32 = 0]) As System.Collections.IEnumerator</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub) End Sub <Fact()> Public Sub DefaultProperty1() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Reflection.DefaultMember("p1")> Public Class ComClassTest Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property Event E1 As Action End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>p1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Event Name="E1"> <EventFlags></EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub DispId18() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property <DispId(-1)> Sub M1() End Sub <DispId(-2)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'P1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. ReadOnly Property P1(x As Integer) As Integer ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Sub M1() ~~ BC32506: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves values less than zero. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DispId19() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Sub M1() End Sub <DispId(0)> Event E1 As Action End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'M1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Sub M1() ~~ BC32505: 'System.Runtime.InteropServices.DispIdAttribute' cannot be applied to 'E1' because 'Microsoft.VisualBasic.ComClassAttribute' reserves zero for the default property. Event E1 As Action ~~ </expected>) End Sub <Fact()> Public Sub DefaultProperty2() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass()> Public Class ComClassTest <DispId(0)> Default ReadOnly Property P1(x As Integer) As Integer Get Return Nothing End Get End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Implements> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> <System.Reflection.DefaultMemberAttribute> <ctor>Sub System.Reflection.DefaultMemberAttribute..ctor(memberName As System.String)</ctor> <a>P1</a> </System.Reflection.DefaultMemberAttribute> </Attributes> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Integer</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>0</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1(x As System.Int32) As System.Int32</Get> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact()> Public Sub Serializable_and_SpecialName() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System <Microsoft.VisualBasic.ComClass()> <Serializable()> <System.Runtime.CompilerServices.SpecialName()> Public Class ComClassTest <System.Runtime.CompilerServices.SpecialName()> Sub M1() End Sub <System.Runtime.CompilerServices.SpecialName()> Event E1 As Action <System.Runtime.CompilerServices.SpecialName()> Property P1 As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property P2 As Integer <System.Runtime.CompilerServices.SpecialName()> Get Return 0 End Get <System.Runtime.CompilerServices.SpecialName()> Set(value As Integer) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClassTest"> <TypeDefFlags>public auto ansi serializable specialname</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <System.Runtime.InteropServices.ComSourceInterfacesAttribute> <ctor>Sub System.Runtime.InteropServices.ComSourceInterfacesAttribute..ctor(sourceInterfaces As System.String)</ctor> <a>ComClassTest+__ComClassTest</a> </System.Runtime.InteropServices.ComSourceInterfacesAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor()</ctor> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClassTest._ComClassTest</Implements> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.M1()</Implements> <Return> <Type>Void</Type> </Return> </Method> <Method Name="add_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="remove_E1" CallingConvention="HasThis"> <MethodFlags>public specialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.CompilerServices.CompilerGeneratedAttribute> <ctor>Sub System.Runtime.CompilerServices.CompilerGeneratedAttribute..ctor()</ctor> </System.Runtime.CompilerServices.CompilerGeneratedAttribute> </Attributes> <Parameter Name="obj"> <ParamFlags></ParamFlags> <Type>System.Action</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Implements> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Implements> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Get>Function ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Get>Function ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest.set_P2(value As System.Int32)</Set> </Property> <Event Name="E1"> <EventFlags>specialname</EventFlags> <Add>Sub ComClassTest.add_E1(obj As System.Action)</Add> <Remove>Sub ComClassTest.remove_E1(obj As System.Action)</Remove> </Event> <Interface Name="_ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="M1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Integer</Type> </Return> </Method> <Method Name="set_P2" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="value"> <ParamFlags></ParamFlags> <Type>Integer</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="P1"> <PropertyFlags>specialname</PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>2</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P1() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P1(value As System.Int32)</Set> </Property> <Property Name="P2"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>3</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClassTest._ComClassTest.get_P2() As System.Int32</Get> <Set>Sub ComClassTest._ComClassTest.set_P2(value As System.Int32)</Set> </Property> </Interface> <Interface Name="__ComClassTest"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.InterfaceTypeAttribute> <ctor>Sub System.Runtime.InteropServices.InterfaceTypeAttribute..ctor(interfaceType As System.Int16)</ctor> <a>2</a> </System.Runtime.InteropServices.InterfaceTypeAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="E1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>Void</Type> </Return> </Method> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClassTest")) End Sub).VerifyDiagnostics() End Sub <Fact(), WorkItem(531506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531506")> Public Sub Bug18218() Dim compilationDef = <compilation name="SimpleTest1"> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Assembly: GuidAttribute("5F025F24-FAEA-4C2F-9EF6-C89A8FC90101")> <Assembly: ComVisible(True)> <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Implements I6 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F" Public Const InterfaceId As String = "5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512" Public Const EventsId As String = "33241EB2-DFC5-4164-998E-A6577B0DA960" #End Region Public Interface I6 End Interface Public Property Scen1 As String Get Return Nothing End Get Set(ByVal Value As String) End Set End Property End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>5D025F24-FAEA-4C2F-9EF6-C89A8FC9667F</a> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> <a>33241EB2-DFC5-4164-998E-A6577B0DA960</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Implements>ComClass1.I6</Implements> <Field Name="ClassId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="InterfaceId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Field Name="EventsId"> <FieldFlags>public static literal default</FieldFlags> <Type>String</Type> </Field> <Method Name=".ctor" CallingConvention="HasThis"> <MethodFlags>public specialname rtspecialname instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Return> <Type>Void</Type> </Return> </Method> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.get_Scen1() As System.String</Implements> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Implements> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Get>Function ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1.set_Scen1(Value As System.String)</Set> </Property> <Interface Name="I6"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> </Interface> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>5FDA4272-D6AD-4FA4-AD89-FAB8F0A04512</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="get_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Return> <Type>String</Type> </Return> </Method> <Method Name="set_Scen1" CallingConvention="HasThis"> <MethodFlags>public newslot strict specialname abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="Value"> <ParamFlags></ParamFlags> <Type>String</Type> </Parameter> <Return> <Type>Void</Type> </Return> </Method> <Property Name="Scen1"> <PropertyFlags></PropertyFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Get>Function ComClass1._ComClass1.get_Scen1() As System.String</Get> <Set>Sub ComClass1._ComClass1.set_Scen1(Value As System.String)</Set> </Property> </Interface> </Class> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1")) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664574")> Public Sub Bug664574() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Imports System.Runtime.InteropServices <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Function dfoo(<MarshalAs(UnmanagedType.Currency)> ByVal x As Decimal) As <MarshalAs(UnmanagedType.Currency)> Decimal Return x + 1.1D End Function End Class ]]></file> </compilation> Dim expected = <Class Name="ComClass1"> <TypeDefFlags>public auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ClassInterfaceAttribute> <ctor>Sub System.Runtime.InteropServices.ClassInterfaceAttribute..ctor(classInterfaceType As System.Runtime.InteropServices.ClassInterfaceType)</ctor> <a>0</a> </System.Runtime.InteropServices.ClassInterfaceAttribute> <Microsoft.VisualBasic.ComClassAttribute> <ctor>Sub Microsoft.VisualBasic.ComClassAttribute..ctor(_ClassID As System.String, _InterfaceID As System.String, _EventId As System.String)</ctor> <a>C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B</a> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> <a>8F12C15B-4CA9-450C-9C85-37E9B74164B8</a> </Microsoft.VisualBasic.ComClassAttribute> </Attributes> <Implements>ComClass1._ComClass1</Implements> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict virtual final instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Implements>Function ComClass1._ComClass1.dfoo(x As System.Decimal) As System.Decimal</Implements> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> <Interface Name="_ComClass1"> <TypeDefFlags>interface nested public abstract auto ansi</TypeDefFlags> <Attributes> <System.Runtime.InteropServices.GuidAttribute> <ctor>Sub System.Runtime.InteropServices.GuidAttribute..ctor(guid As System.String)</ctor> <a>E4174EC8-7EDD-4672-90BA-3D1CFFF76C14</a> </System.Runtime.InteropServices.GuidAttribute> <System.Runtime.InteropServices.ComVisibleAttribute> <ctor>Sub System.Runtime.InteropServices.ComVisibleAttribute..ctor(visibility As System.Boolean)</ctor> <a>True</a> </System.Runtime.InteropServices.ComVisibleAttribute> </Attributes> <Method Name="dfoo" CallingConvention="HasThis"> <MethodFlags>public newslot strict abstract virtual instance</MethodFlags> <MethodImplFlags>cil managed</MethodImplFlags> <Attributes> <System.Runtime.InteropServices.DispIdAttribute> <ctor>Sub System.Runtime.InteropServices.DispIdAttribute..ctor(dispId As System.Int32)</ctor> <a>1</a> </System.Runtime.InteropServices.DispIdAttribute> </Attributes> <Parameter Name="x"> <ParamFlags>marshal</ParamFlags> <Type>Decimal</Type> </Parameter> <Return> <Type>Decimal</Type> <ParamFlags>marshal</ParamFlags> </Return> </Method> </Interface> </Class> ' Strip TODO comments from the base-line. For Each d In expected.DescendantNodes.ToArray() Dim comment = TryCast(d, XComment) If comment IsNot Nothing Then comment.Remove() End If Next Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim pe = DirectCast(m, PEModuleSymbol) AssertReflection(expected, ReflectComClass(pe, "ComClass1", Function(s) Return s.Kind = SymbolKind.NamedType OrElse s.Name = "dfoo" End Function)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(664583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/664583")> Public Sub Bug664583() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 #Region "COM GUIDs" ' These GUIDs provide the COM identity for this class ' and its COM interfaces. If you change them, existing ' clients will no longer be able to access the class. Public Const ClassId As String = "C1F1CEC8-2BDD-4AFC-8E86-FDC8DBEE951B" Public Const InterfaceId As String = "E4174EC8-7EDD-4672-90BA-3D1CFFF76C14" Public Const EventsId As String = "8F12C15B-4CA9-450C-9C85-37E9B74164B8" #End Region Public Readonly Property Goo As Integer Get Return 0 End Get End Property Structure Struct1 Public member1 As Integer Structure Struct2 Public member12 As Integer End Structure End Structure Structure struct2 Public member2 As Integer End Structure End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim ComClass1_Struct1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1"), PENamedTypeSymbol) Dim ComClass1_Struct1_Struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+Struct1+Struct2"), PENamedTypeSymbol) Dim ComClass1_struct2 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+struct2"), PENamedTypeSymbol) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_Struct1.Handle) < MetadataTokens.GetRowNumber(ComClass1_struct2.Handle)) Assert.True(MetadataTokens.GetRowNumber(ComClass1_struct2.Handle) < MetadataTokens.GetRowNumber(ComClass1_Struct1_Struct2.Handle)) End Sub).VerifyDiagnostics() End Sub <Fact, WorkItem(700050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700050")> Public Sub Bug700050() Dim compilationDef = <compilation> <file name="a.vb"><![CDATA[ Module Module1 Sub Main() End Sub End Module <Microsoft.VisualBasic.ComClass(ComClass1.ClassId, ComClass1.InterfaceId, ComClass1.EventsId)> Public Class ComClass1 Public Const ClassId As String = "" Public Const InterfaceId As String = "" Public Const EventsId As String = "" Public Sub New() End Sub Public Sub Goo() End Sub Public Property oBrowser As Object ' cannot be exposed to COM as a property 'Let'. You will not be able to assign non-object values (such as numbers or strings) to this property from Visual Basic 6.0 using a 'Let' statement. End Class ]]></file> </compilation> Dim verifier = CompileAndVerify(compilationDef, options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal), symbolValidator:=Sub(m As ModuleSymbol) Dim _ComClass1 = DirectCast(m.ContainingAssembly.GetTypeByMetadataName("ComClass1+_ComClass1"), PENamedTypeSymbol) Assert.Equal(0, _ComClass1.GetMembers("oBrowser").Length) End Sub).VerifyDiagnostics() End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Interactive/HostProcess/InteractiveHostEntryPoint.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.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.Interactive { internal static class InteractiveHostEntryPoint { private static async Task<int> Main(string[] args) { FatalError.Handler = FailFast.OnFatalException; // Disables Windows Error Reporting for the process, so that the process fails fast. SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); Control? control = null; using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { control = new Control(); control.CreateControl(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } var invokeOnMainThread = new Func<Func<object>, object>(operation => control!.Invoke(operation)); try { await InteractiveHost.Service.RunServerAsync(args, invokeOnMainThread).ConfigureAwait(false); return 0; } catch (Exception e) { Console.Error.WriteLine(e); return 1; } } [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from blocking the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.Interactive { internal static class InteractiveHostEntryPoint { private static async Task<int> Main(string[] args) { FatalError.Handler = FailFast.OnFatalException; // Disables Windows Error Reporting for the process, so that the process fails fast. SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX); Control? control = null; using (var resetEvent = new ManualResetEventSlim(false)) { var uiThread = new Thread(() => { control = new Control(); control.CreateControl(); resetEvent.Set(); Application.Run(); }); uiThread.SetApartmentState(ApartmentState.STA); uiThread.IsBackground = true; uiThread.Start(); resetEvent.Wait(); } var invokeOnMainThread = new Func<Func<object>, object>(operation => control!.Invoke(operation)); try { await InteractiveHost.Service.RunServerAsync(args, invokeOnMainThread).ConfigureAwait(false); return 0; } catch (Exception e) { Console.Error.WriteLine(e); return 1; } } [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode SetErrorMode(ErrorMode mode); [DllImport("kernel32", PreserveSig = true)] internal static extern ErrorMode GetErrorMode(); [Flags] internal enum ErrorMode : int { /// <summary> /// Use the system default, which is to display all error dialog boxes. /// </summary> SEM_FAILCRITICALERRORS = 0x0001, /// <summary> /// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process. /// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup. /// This is to prevent error mode dialogs from blocking the application. /// </summary> SEM_NOGPFAULTERRORBOX = 0x0002, /// <summary> /// The system automatically fixes memory alignment faults and makes them invisible to the application. /// It does this for the calling process and any descendant processes. This feature is only supported by /// certain processor architectures. For more information, see the Remarks section. /// After this value is set for a process, subsequent attempts to clear the value are ignored. /// </summary> SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, /// <summary> /// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process. /// </summary> SEM_NOOPENFILEERRORBOX = 0x8000, } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => 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.Generic; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IUsingStatement.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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.Operations Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")> Public Sub UsingDeclarationSyntaxNotNull() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using D1 as New C1() End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.NotNull(op.Resources.Syntax) Assert.Same(node.UsingStatement, op.Resources.Syntax) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")> Public Sub UsingDeclarationIncompleteUsingInvalidExpression() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30201: Expression expected. Using ~ </expected>) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.Equal(OperationKind.Invalid, op.Resources.Kind) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IUsingStatement_MultipleNewResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As ... s C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"Using c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleAsNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MultipleAsNewResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1, c2 As New C'BIND:"Using c1, c2 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1, c2 As New C') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1, c2 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleExistingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidMultipleExistingResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1, c2'BIND:"Using c1, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As System.Object Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1, c2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1, c2') Declarators: IVariableDeclaratorOperation (Symbol: c1 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c1' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1, c2'BIND:"Using c1, c2" ~~ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(c1) ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_NestedUsing() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1'BIND:"Using c1" Using c2 Console.WriteLine(c1) End Using End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c2 ... End Using') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c2 ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MixedAsNewAndSingleInitializer() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Local_3: c3 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c3 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2, c3 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null IVariableDeclaratorOperation (Symbol: c3 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNoInitializerOneVariable() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c2 As New C Using c1 = New C, c2'BIND:"Using c1 = New C, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 = New C, c2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c2') Declarators: IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNonDisposableResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C, IsInvalid) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'. Using c1 As New C'BIND:"Using c1 As New C" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidEmptyUsingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using'BIND:"Using" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using'BIND: ... End Using') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Using'BIND:"Using" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNothingResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using Nothing'BIND:"Using Nothing" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using Nothi ... End Using') Resources: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'. Using Nothing'BIND:"Using Nothing" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingWithoutSavedReference() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using GetC()'BIND:"Using GetC()" End Using End Sub Function GetC() As C Return New C End Function Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using GetC( ... End Using') Resources: IInvocationOperation (Function Program.GetC() As Program.C) (OperationKind.Invocation, Type: Program.C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using GetC( ... End Using') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c2 = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource() Dim source = <compilation> <file Name="a.vb"> <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"c1 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingStatementSyntax_Expression() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C Console.WriteLine()'BIND:"Console.WriteLine()" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()') Expression: IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer) 'BIND:"Sub M" Using c1 As C1 = New C1, s2 As S2 = New S2 x = 1 End Using End Sub End Class Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Structure S2 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [c1 As C1] [s2 As S2] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'c1 As C1 = New C1') Left: ILocalReferenceOperation: c1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S2, IsImplicit) (Syntax: 's2 As S2 = New S2') Left: ILocalReferenceOperation: s2 (IsDeclaration: True) (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Right: IObjectCreationOperation (Constructor: Sub S2..ctor()) (OperationKind.ObjectCreation, Type: S2) (Syntax: 'New S2') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's2') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 's2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILocalReferenceOperation: s2 (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c1') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using Nothing End Using End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Nothing') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNothingLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'Nothing') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'Nothing') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_NotDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'D' must implement 'System.IDisposable'. Using New D() ~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D, IsInvalid) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'New D()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_Missing_IDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class ]]>.Value Dim compilation = CreateCompilation(source) compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'New D()') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) 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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.Operations Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19819, "https://github.com/dotnet/roslyn/issues/19819")> Public Sub UsingDeclarationSyntaxNotNull() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using D1 as New C1() End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.NotNull(op.Resources.Syntax) Assert.Same(node.UsingStatement, op.Resources.Syntax) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> <WorkItem(19887, "https://github.com/dotnet/roslyn/issues/19887")> Public Sub UsingDeclarationIncompleteUsingInvalidExpression() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module Module1 Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Sub S1() Using End Using End Sub End Module ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30201: Expression expected. Using ~ </expected>) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single() Dim op = DirectCast(comp.GetSemanticModel(tree).GetOperation(node), IUsingOperation) Assert.Equal(OperationKind.Invalid, op.Resources.Kind) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub IUsingStatement_MultipleNewResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C, c2 As C = New C'BIND:"Using c1 As C = New C, c2 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As ... s C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As C = New C'BIND:"Using c1 As C = New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As C = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As C = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleAsNewResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MultipleAsNewResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1, c2 As New C'BIND:"Using c1, c2 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1, c2 As New C') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1, c2 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_SingleExistingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidMultipleExistingResources() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1, c2'BIND:"Using c1, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1, c ... End Using') Locals: Local_1: c1 As System.Object Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1, c2') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1, c2') Declarators: IVariableDeclaratorOperation (Symbol: c1 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1, c ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Object) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c1' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1, c2'BIND:"Using c1, c2" ~~ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1, c2'BIND:"Using c1, c2" ~~ BC42104: Variable 'c1' is used before it has been assigned a value. A null reference exception could result at runtime. Console.WriteLine(c1) ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_NestedUsing() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c1, c2 As New C Using c1'BIND:"Using c1" Using c2 Console.WriteLine(c1) End Using End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1'BI ... End Using') Resources: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1'BI ... End Using') IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c2 ... End Using') Resources: ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c2') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c2 ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_MixedAsNewAndSingleInitializer() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Using c1 = New C, c2, c3 As New C'BIND:"Using c1 = New C, c2, c3 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As Program.C Local_3: c3 As Program.C Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c3 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2, c3 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null IVariableDeclaratorOperation (Symbol: c3 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c3') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNoInitializerOneVariable() Dim source = <![CDATA[ Imports System Module Program Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class Sub Main(args As String()) Dim c2 As New C Using c1 = New C, c2'BIND:"Using c1 = New C, c2" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 = ... End Using') Locals: Local_1: c1 As Program.C Local_2: c2 As System.Object Resources: IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 = New C, c2') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c2') Declarators: IVariableDeclaratorOperation (Symbol: c2 As System.Object) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c2') Initializer: null Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 = ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30616: Variable 'c2' hides a variable in an enclosing block. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ BC36011: 'Using' resource variable must have an explicit initialization. Using c1 = New C, c2'BIND:"Using c1 = New C, c2" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNonDisposableResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Class C End Class Sub Main(args As String()) Using c1 As New C'BIND:"Using c1 As New C" Console.WriteLine(c1) End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using c1 As ... End Using') Locals: Local_1: c1 As Program.C Resources: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Using c1 As New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c1 As New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: 'As New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C, IsInvalid) (Syntax: 'New C') Arguments(0) Initializer: null Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using c1 As ... End Using') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(c1)') Expression: IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(c1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'c1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Program.C' must implement 'System.IDisposable'. Using c1 As New C'BIND:"Using c1 As New C" ~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidEmptyUsingResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using'BIND:"Using" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using'BIND: ... End Using') Resources: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using'BIND: ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30201: Expression expected. Using'BIND:"Using" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_InvalidNothingResources() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using Nothing'BIND:"Using Nothing" End Using End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null, IsInvalid) (Syntax: 'Using Nothi ... End Using') Resources: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'Nothing') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Using Nothi ... End Using') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'Object' must implement 'System.IDisposable'. Using Nothing'BIND:"Using Nothing" ~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingWithoutSavedReference() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using GetC()'BIND:"Using GetC()" End Using End Sub Function GetC() As C Return New C End Function Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IUsingOperation (OperationKind.Using, Type: null) (Syntax: 'Using GetC( ... End Using') Resources: IInvocationOperation (Function Program.GetC() As Program.C) (OperationKind.Invocation, Type: Program.C) (Syntax: 'GetC()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Using GetC( ... End Using') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithDeclarationResource() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"Using c1 = New C, c2 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationGroupOperation (2 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Using c1 = ... c2 = New C') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c2 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c2 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c2') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of UsingStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_UsingStatementSyntax_WithExpressionResource() Dim source = <compilation> <file Name="a.vb"> <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"Using c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) CompilationUtils.AssertNoDiagnostics(comp) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of UsingBlockSyntax).Single().UsingStatement Assert.Null(comp.GetSemanticModel(node.SyntaxTree).GetOperation(node)) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact, WorkItem(22362, "https://github.com/dotnet/roslyn/issues/22362")> Public Sub IUsingStatement_UsingStatementSyntax_VariablesSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C'BIND:"c1 = New C" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'c1 = New C') Declarators: IVariableDeclaratorOperation (Symbol: c1 As Program.C) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c1') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= New C') IObjectCreationOperation (Constructor: Sub Program.C..ctor()) (OperationKind.ObjectCreation, Type: Program.C) (Syntax: 'New C') Arguments(0) Initializer: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of VariableDeclaratorSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingStatementSyntax_Expression() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Dim c1 As New C Using c1'BIND:"c1" Console.WriteLine() End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: Program.C) (Syntax: 'c1') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IUsingStatement_UsingBlockSyntax_StatementsSyntax() Dim source = <![CDATA[ Option Strict On Imports System Module Program Sub Main(args As String()) Using c1 = New C, c2 = New C Console.WriteLine()'BIND:"Console.WriteLine()" End Using End Sub Class C Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()') Expression: IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_14() Dim source = <![CDATA[ Imports System Public Class C Sub M(x As Integer) 'BIND:"Sub M" Using c1 As C1 = New C1, s2 As S2 = New S2 x = 1 End Using End Sub End Class Class C1 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Class Structure S2 Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose Throw New NotImplementedException() End Sub End Structure ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [c1 As C1] [s2 As S2] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'c1 As C1 = New C1') Left: ILocalReferenceOperation: c1 (IsDeclaration: True) (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Right: IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: S2, IsImplicit) (Syntax: 's2 As S2 = New S2') Left: ILocalReferenceOperation: s2 (IsDeclaration: True) (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Right: IObjectCreationOperation (Constructor: Sub S2..ctor()) (OperationKind.ObjectCreation, Type: S2) (Syntax: 'New S2') Arguments(0) Initializer: null Next (Regular) Block[B3] Entering: {R4} {R5} .try {R4, R5} { Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Finalizing: {R6} {R7} Leaving: {R5} {R4} {R3} {R2} {R1} } .finally {R6} { Block[B4] - Block Predecessors (0) Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 's2') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 's2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningValue) Operand: ILocalReferenceOperation: s2 (OperationKind.LocalReference, Type: S2, IsImplicit) (Syntax: 's2') Arguments(0) Next (StructuredExceptionHandling) Block[null] } } .finally {R7} { Block[B5] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'c1') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'c1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: C1, IsImplicit) (Syntax: 'c1') Arguments(0) Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B8] - Exit Predecessors: [B3] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_15() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using Nothing End Using End Sub End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Nothing') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (WideningNothingLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'Nothing') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Next (Regular) Block[B4] Block[B4] - Block [UnReachable] Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'Nothing') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_NotDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D End Class ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36010: 'Using' operand of type 'D' must implement 'System.IDisposable'. Using New D() ~~~~~~~ ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D, IsInvalid) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'New D()') Instance Receiver: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsInvalid, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (NarrowingReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsInvalid, IsImplicit) (Syntax: 'New D()') Arguments(0) Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub UsingFlow_Missing_IDisposable() Dim source = <![CDATA[ Imports System Public Class C Sub M() 'BIND:"Sub M" Using New D() End Using End Sub End Class Public Class D Implements IDisposable Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class ]]>.Value Dim compilation = CreateCompilation(source) compilation.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose) Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'New D()') Value: IObjectCreationOperation (Constructor: Sub D..ctor()) (OperationKind.ObjectCreation, Type: D) (Syntax: 'New D()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} {R3} .try {R2, R3} { Block[B2] - Block Predecessors: [B1] Statements (0) Next (Regular) Block[B6] Finalizing: {R4} Leaving: {R3} {R2} {R1} } .finally {R4} { Block[B3] - Block Predecessors (0) Statements (0) Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'New D()') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IInvalidOperation (OperationKind.Invalid, Type: null, IsImplicit) (Syntax: 'New D()') Children(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'New D()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (WideningReference) Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: D, IsImplicit) (Syntax: 'New D()') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Next (StructuredExceptionHandling) Block[null] } } Block[B6] - Exit Predecessors: [B2] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
56,229
Merge all source generator state in CompilationTracker into a helper type.
Followup to https://github.com/dotnet/roslyn/pull/56139
CyrusNajmabadi
"2021-09-07T22:19:24Z"
"2021-09-09T00:43:30Z"
5a0a1c2c368c679fd15196078420a0079ba9f340
897c0d1a277876f02c5d902731b95f2b7cb8e587
Merge all source generator state in CompilationTracker into a helper type.. Followup to https://github.com/dotnet/roslyn/pull/56139
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ParameterSymbolReferenceFinder : AbstractReferenceFinder<IParameterSymbol> { protected override bool CanFind(IParameterSymbol symbol) => true; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IParameterSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // TODO(cyrusn): We can be smarter with parameters. They will either be found // within the method that they were declared on, or they will referenced // elsewhere as "paramName:" or "paramName:=". We can narrow the search by // filtering down to matches of that form. For now we just return any document // that references something with this name. return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IParameterSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var symbolsMatchAsync = GetParameterSymbolsMatchFunction(symbol, document.Project.Solution, cancellationToken); return FindReferencesInDocumentUsingIdentifierAsync( symbol, symbol.Name, document, semanticModel, symbolsMatchAsync, cancellationToken); } private static Func<SyntaxToken, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>> GetParameterSymbolsMatchFunction( IParameterSymbol parameter, Solution solution, CancellationToken cancellationToken) { // Get the standard function for comparing parameters. This function will just // directly compare the parameter symbols for SymbolEquivalence. var standardFunction = GetStandardSymbolsMatchFunction(parameter, findParentNode: null, solution, cancellationToken); // HOwever, we also want to consider parameter symbols them same if they unify across // VB's synthesized AnonymousDelegate parameters. var containingMethod = parameter.ContainingSymbol as IMethodSymbol; if (containingMethod?.AssociatedAnonymousDelegate == null) { // This was a normal parameter, so just use the normal comparison function. return standardFunction; } var invokeMethod = containingMethod.AssociatedAnonymousDelegate.DelegateInvokeMethod; var ordinal = parameter.Ordinal; if (invokeMethod == null || ordinal >= invokeMethod.Parameters.Length) { return standardFunction; } // This was parameter of a method that had an associated synthesized anonyomous-delegate. // IN that case, we want it to match references to the corresponding parameter in that // anonymous-delegate's invoke method. So get he symbol match function that will chec // for equivalence with that parameter. var anonymousDelegateParameter = invokeMethod.Parameters[ordinal]; var anonParameterFunc = GetStandardSymbolsMatchFunction(anonymousDelegateParameter, findParentNode: null, solution, cancellationToken); // Return a new function which is a compound of the two functions we have. return async (token, model) => { // First try the standard function. var result = await standardFunction(token, model).ConfigureAwait(false); if (!result.matched) { // If it fails, fall back to the anon-delegate function. result = await anonParameterFunc(token, model).ConfigureAwait(false); } return result; }; } protected override async Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IParameterSymbol parameter, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (parameter.IsThis) { return ImmutableArray<ISymbol>.Empty; } using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var symbols); await CascadeBetweenAnonymousFunctionParametersAsync(solution, parameter, symbols, cancellationToken).ConfigureAwait(false); CascadeBetweenPropertyAndAccessorParameters(parameter, symbols); CascadeBetweenDelegateMethodParameters(parameter, symbols); CascadeBetweenPartialMethodParameters(parameter, symbols); return symbols.ToImmutable(); } private static async Task CascadeBetweenAnonymousFunctionParametersAsync( Solution solution, IParameterSymbol parameter, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { if (parameter.ContainingSymbol.IsAnonymousFunction()) { var parameterNode = parameter.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (parameterNode != null) { var document = solution.GetDocument(parameterNode.SyntaxTree); if (document != null) { var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); if (semanticFacts.ExposesAnonymousFunctionParameterNames) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType != null) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var container = GetContainer(semanticModel, parameterNode, syntaxFacts); if (container != null) { CascadeBetweenAnonymousFunctionParameters( document, semanticModel, container, parameter, convertedType, results, cancellationToken); } } } } } } } private static void CascadeBetweenAnonymousFunctionParameters( Document document, SemanticModel semanticModel, SyntaxNode container, IParameterSymbol parameter, ITypeSymbol convertedType1, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var token in container.DescendantTokens()) { if (IdentifiersMatch(syntaxFacts, parameter.Name, token)) { var symbol = semanticModel.GetDeclaredSymbol(token.GetRequiredParent(), cancellationToken); if (symbol is IParameterSymbol && symbol.ContainingSymbol.IsAnonymousFunction() && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(parameter.ContainingSymbol, symbol.ContainingSymbol, syntaxFacts.IsCaseSensitive) && ParameterNamesMatch(syntaxFacts, (IMethodSymbol)parameter.ContainingSymbol, (IMethodSymbol)symbol.ContainingSymbol)) { var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType2 = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType1.Equals(convertedType2)) { results.Add(symbol); } } } } } private static bool ParameterNamesMatch(ISyntaxFactsService syntaxFacts, IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) { for (var i = 0; i < methodSymbol1.Parameters.Length; i++) { if (!syntaxFacts.TextMatch(methodSymbol1.Parameters[i].Name, methodSymbol2.Parameters[i].Name)) { return false; } } return true; } private static SyntaxNode? GetContainer(SemanticModel semanticModel, SyntaxNode parameterNode, ISyntaxFactsService syntaxFactsService) { for (var current = parameterNode; current != null; current = current.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(current); if (declaredSymbol is IMethodSymbol method && method.MethodKind != MethodKind.AnonymousFunction) { return current; } } return syntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration(parameterNode); } private static void CascadeBetweenPropertyAndAccessorParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; var containingSymbol = parameter.ContainingSymbol; if (containingSymbol is IMethodSymbol containingMethod) { if (containingMethod.AssociatedSymbol is IPropertySymbol property) { AddParameterAtIndex(results, ordinal, property.Parameters); } } else if (containingSymbol is IPropertySymbol containingProperty) { if (containingProperty.GetMethod != null && ordinal < containingProperty.GetMethod.Parameters.Length) { results.Add(containingProperty.GetMethod.Parameters[ordinal]); } if (containingProperty.SetMethod != null && ordinal < containingProperty.SetMethod.Parameters.Length) { results.Add(containingProperty.SetMethod.Parameters[ordinal]); } } } private static void CascadeBetweenDelegateMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; if (parameter.ContainingSymbol is IMethodSymbol containingMethod) { var containingType = containingMethod.ContainingType; if (containingType.IsDelegateType()) { if (containingMethod.MethodKind == MethodKind.DelegateInvoke) { // cascade to the corresponding parameter in the BeginInvoke method. var beginInvokeMethod = containingType.GetMembers(WellKnownMemberNames.DelegateBeginInvokeName) .OfType<IMethodSymbol>() .FirstOrDefault(); AddParameterAtIndex(results, ordinal, beginInvokeMethod?.Parameters); } else if (containingMethod.ContainingType.IsDelegateType() && containingMethod.Name == WellKnownMemberNames.DelegateBeginInvokeName) { // cascade to the corresponding parameter in the Invoke method. AddParameterAtIndex(results, ordinal, containingType.DelegateInvokeMethod?.Parameters); } } } } private static void AddParameterAtIndex( ArrayBuilder<ISymbol> results, int ordinal, ImmutableArray<IParameterSymbol>? parameters) { if (parameters != null && ordinal < parameters.Value.Length) { results.Add(parameters.Value[ordinal]); } } private static void CascadeBetweenPartialMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { if (parameter.ContainingSymbol is IMethodSymbol) { var ordinal = parameter.Ordinal; var method = (IMethodSymbol)parameter.ContainingSymbol; if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.Parameters.Length) { results.Add(method.PartialDefinitionPart.Parameters[ordinal]); } if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.Parameters.Length) { results.Add(method.PartialImplementationPart.Parameters[ordinal]); } } } } }
// 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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ParameterSymbolReferenceFinder : AbstractReferenceFinder<IParameterSymbol> { protected override bool CanFind(IParameterSymbol symbol) => true; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IParameterSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // TODO(cyrusn): We can be smarter with parameters. They will either be found // within the method that they were declared on, or they will referenced // elsewhere as "paramName:" or "paramName:=". We can narrow the search by // filtering down to matches of that form. For now we just return any document // that references something with this name. return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IParameterSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var symbolsMatchAsync = GetParameterSymbolsMatchFunction(symbol, document.Project.Solution, cancellationToken); return FindReferencesInDocumentUsingIdentifierAsync( symbol, symbol.Name, document, semanticModel, symbolsMatchAsync, cancellationToken); } private static Func<SyntaxToken, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>> GetParameterSymbolsMatchFunction( IParameterSymbol parameter, Solution solution, CancellationToken cancellationToken) { // Get the standard function for comparing parameters. This function will just // directly compare the parameter symbols for SymbolEquivalence. var standardFunction = GetStandardSymbolsMatchFunction(parameter, findParentNode: null, solution, cancellationToken); // HOwever, we also want to consider parameter symbols them same if they unify across // VB's synthesized AnonymousDelegate parameters. var containingMethod = parameter.ContainingSymbol as IMethodSymbol; if (containingMethod?.AssociatedAnonymousDelegate == null) { // This was a normal parameter, so just use the normal comparison function. return standardFunction; } var invokeMethod = containingMethod.AssociatedAnonymousDelegate.DelegateInvokeMethod; var ordinal = parameter.Ordinal; if (invokeMethod == null || ordinal >= invokeMethod.Parameters.Length) { return standardFunction; } // This was parameter of a method that had an associated synthesized anonyomous-delegate. // IN that case, we want it to match references to the corresponding parameter in that // anonymous-delegate's invoke method. So get he symbol match function that will chec // for equivalence with that parameter. var anonymousDelegateParameter = invokeMethod.Parameters[ordinal]; var anonParameterFunc = GetStandardSymbolsMatchFunction(anonymousDelegateParameter, findParentNode: null, solution, cancellationToken); // Return a new function which is a compound of the two functions we have. return async (token, model) => { // First try the standard function. var result = await standardFunction(token, model).ConfigureAwait(false); if (!result.matched) { // If it fails, fall back to the anon-delegate function. result = await anonParameterFunc(token, model).ConfigureAwait(false); } return result; }; } protected override async Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IParameterSymbol parameter, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { if (parameter.IsThis) { return ImmutableArray<ISymbol>.Empty; } using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var symbols); await CascadeBetweenAnonymousFunctionParametersAsync(solution, parameter, symbols, cancellationToken).ConfigureAwait(false); CascadeBetweenPropertyAndAccessorParameters(parameter, symbols); CascadeBetweenDelegateMethodParameters(parameter, symbols); CascadeBetweenPartialMethodParameters(parameter, symbols); return symbols.ToImmutable(); } private static async Task CascadeBetweenAnonymousFunctionParametersAsync( Solution solution, IParameterSymbol parameter, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { if (parameter.ContainingSymbol.IsAnonymousFunction()) { var parameterNode = parameter.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (parameterNode != null) { var document = solution.GetDocument(parameterNode.SyntaxTree); if (document != null) { var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); if (semanticFacts.ExposesAnonymousFunctionParameterNames) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType != null) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var container = GetContainer(semanticModel, parameterNode, syntaxFacts); if (container != null) { CascadeBetweenAnonymousFunctionParameters( document, semanticModel, container, parameter, convertedType, results, cancellationToken); } } } } } } } private static void CascadeBetweenAnonymousFunctionParameters( Document document, SemanticModel semanticModel, SyntaxNode container, IParameterSymbol parameter, ITypeSymbol convertedType1, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var token in container.DescendantTokens()) { if (IdentifiersMatch(syntaxFacts, parameter.Name, token)) { var symbol = semanticModel.GetDeclaredSymbol(token.GetRequiredParent(), cancellationToken); if (symbol is IParameterSymbol && symbol.ContainingSymbol.IsAnonymousFunction() && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(parameter.ContainingSymbol, symbol.ContainingSymbol, syntaxFacts.IsCaseSensitive) && ParameterNamesMatch(syntaxFacts, (IMethodSymbol)parameter.ContainingSymbol, (IMethodSymbol)symbol.ContainingSymbol)) { var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType2 = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType1.Equals(convertedType2)) { results.Add(symbol); } } } } } private static bool ParameterNamesMatch(ISyntaxFactsService syntaxFacts, IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) { for (var i = 0; i < methodSymbol1.Parameters.Length; i++) { if (!syntaxFacts.TextMatch(methodSymbol1.Parameters[i].Name, methodSymbol2.Parameters[i].Name)) { return false; } } return true; } private static SyntaxNode? GetContainer(SemanticModel semanticModel, SyntaxNode parameterNode, ISyntaxFactsService syntaxFactsService) { for (var current = parameterNode; current != null; current = current.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(current); if (declaredSymbol is IMethodSymbol method && method.MethodKind != MethodKind.AnonymousFunction) { return current; } } return syntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration(parameterNode); } private static void CascadeBetweenPropertyAndAccessorParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; var containingSymbol = parameter.ContainingSymbol; if (containingSymbol is IMethodSymbol containingMethod) { if (containingMethod.AssociatedSymbol is IPropertySymbol property) { AddParameterAtIndex(results, ordinal, property.Parameters); } } else if (containingSymbol is IPropertySymbol containingProperty) { if (containingProperty.GetMethod != null && ordinal < containingProperty.GetMethod.Parameters.Length) { results.Add(containingProperty.GetMethod.Parameters[ordinal]); } if (containingProperty.SetMethod != null && ordinal < containingProperty.SetMethod.Parameters.Length) { results.Add(containingProperty.SetMethod.Parameters[ordinal]); } } } private static void CascadeBetweenDelegateMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; if (parameter.ContainingSymbol is IMethodSymbol containingMethod) { var containingType = containingMethod.ContainingType; if (containingType.IsDelegateType()) { if (containingMethod.MethodKind == MethodKind.DelegateInvoke) { // cascade to the corresponding parameter in the BeginInvoke method. var beginInvokeMethod = containingType.GetMembers(WellKnownMemberNames.DelegateBeginInvokeName) .OfType<IMethodSymbol>() .FirstOrDefault(); AddParameterAtIndex(results, ordinal, beginInvokeMethod?.Parameters); } else if (containingMethod.ContainingType.IsDelegateType() && containingMethod.Name == WellKnownMemberNames.DelegateBeginInvokeName) { // cascade to the corresponding parameter in the Invoke method. AddParameterAtIndex(results, ordinal, containingType.DelegateInvokeMethod?.Parameters); } } } } private static void AddParameterAtIndex( ArrayBuilder<ISymbol> results, int ordinal, ImmutableArray<IParameterSymbol>? parameters) { if (parameters != null && ordinal < parameters.Value.Length) { results.Add(parameters.Value[ordinal]); } } private static void CascadeBetweenPartialMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { if (parameter.ContainingSymbol is IMethodSymbol) { var ordinal = parameter.Ordinal; var method = (IMethodSymbol)parameter.ContainingSymbol; if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.Parameters.Length) { results.Add(method.PartialDefinitionPart.Parameters[ordinal]); } if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.Parameters.Length) { results.Add(method.PartialImplementationPart.Parameters[ordinal]); } } } } }
-1